Deleting an item in ReactJS

后端 未结 2 1551
别那么骄傲
别那么骄傲 2020-12-29 17:48

I\'m new to React and made an app that allows searches to be saved. This will pull JSON but is currently pulling from a static array data. I\'m having trouble

2条回答
  •  暖寄归人
    2020-12-29 18:07

    Let me guess, Are you looking for something like this?

    class Example extends React.Component {
        constructor(){
        this.state = {
          data: [
            {id:1, name: 'Hello'},
            {id:2, name: 'World'},
            {id:3, name: 'How'},
            {id:4, name: 'Are'},
            {id:5, name: 'You'},
            {id:6, name: '?'}
          ]
        }
      }
    
      // shorter & readable 
      delete(item){
        const data = this.state.data.filter(i => i.id !== item.id)
        this.setState({data})
      }
    
      // or this way, it works as well
      //delete(item){
      //  const newState = this.state.data.slice();
      //    if (newState.indexOf(item) > -1) {
      //    newState.splice(newState.indexOf(item), 1);
      //    this.setState({data: newState})
      //  }
      //}
    
      render(){
        const listItem = this.state.data.map((item)=>{
            return 
    {item.name}
    }) return
    {listItem}
    } } React.render(, document.getElementById('container'));

    In this example pay attention how i'm binding delete method and pass there new parameter. fiddle

    I hope it will help you.

    Thanks

提交回复
热议问题