简体   繁体   中英

Change the state value of the property of a particular object that is inside an array

Is there a way to mutate the value of done property of a particular item object in this.state.items when the user checks the checkbox of a targeted <li> ? For example, if I check the checkbox inside an <li> that has an ID of 0 , its done property will change into true .

const Item = props => (
  <li>
    <input type="checkbox" checked={props.done} onChange={props.event} />
    <span>{props.name}</span>
  </li>
)


class Foo extends React.Component {
  state = {
    items: [
      { id: 0, name: 'Item 1', done: false },
      { id: 1, name: 'Item 2', done: false },
      { id: 2, name: 'Item 3', done: false }
    ]
  }

  toggleDone = (e) => {
    // ???
  }

  render() {
    return(
      <ul>
        {this.state.items.map(item => (

          <Item
            key={items.id}
            name={item.name}
            done={item.done}
            event={this.toggleDone} />

        ))}
      </ul>
    )
  }
}

First, you need to pass the index of the item to the event handler.

{this.state.items.map((item,index) => (
   <Item
      key={items.id}
      name={item.name}
      done={item.done}
      event={this.toggleDone.bind(this, index)} />
 ))}

Then, in your event handler, you can change the state like this

toggleDone = (index, e) => {
    // Create new array and new object to avoid state mutation.
    let items = [...this.state.items];
    items[index] = Object.assign({}, items[index], {done: e.target.checked});

    // Set the state with the updated state.
    this.setState({ items });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM