简体   繁体   中英

Use SetState to update one of the item in array object in react

I have a state object called items.

items: [
    {
      name: 'John'
      id: '1',
      checked: false,
    },
    {
      name: 'Dude'
      id: '2',
      checked: true,
    }
]

On UI Click i need to update checked property to true of item with id = 1 How do i use the setState for the items for updating one(single) item in the items

Something like this? Explanation in the comments:

onClick(id) {
  // Create a temporary copy of your items array
  const itemsCopy = this.state.items.slice();

  // Find the index of the items where the item has the id you want
  const idx= itemsCopy.findIndex(x => x.id === id);

  // Re-assign the item to have the same values as before (name and id), but change the checked to true
  itemsCopy[idx] = {...itemsCopy[idx], checked: true};

  // Update the state with our modified copy
  this.setState({items: itemsCopy});
}
const {items} = this.state;
const index = items.findIndex(val=>val.id ===1);
items[index].checked = true;
this.setState({items});

The 'items' object in state should be updated. So slice can be used to copy array. And it should be enough to set it back to state, so component will understand that state is changed.

let items = this.state.items.slice();

const index = items.findIndex(val => val.id === 1);
items[index].checked = true;
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