简体   繁体   English

使用SetState在react中更新数组对象中的一项

[英]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 在UI上,单击“我需要将id = 1的项目的选中属性更新为true”如何将setState用于项目以更新项目中的一个(单个)项目

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. 状态中的“ items”对象应更新。 So slice can be used to copy array. 因此slice可用于复制数组。 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 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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