我有一个称为项目的状态对象。
items: [
{
name: 'John'
id: '1',
checked: false,
},
{
name: 'Dude'
id: '2',
checked: true,
}
]
在UI上单击,我需要将id = 1的项目的检查属性更新为true
我如何将setState用于项目以更新项目中的一个(单个)项目
最佳答案
像这样吗注释中的解释:
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});
}