我正在使用 React,我的状态被定义为对象数组。 我只需要能够更改 state.data 数组中的一个特定元素,即 id 为 1 的示例对象。
我想知道:
- 在这种情况下使用
setState()
的正确方法是什么。
constructor(props) {
super(props);
this.state = {
data: [{
id: 0,
title: 'Buy a',
status: 0, // 0 = todo, 1 = done
},
{
id: 1,
title: 'Buy b',
status: 0,
},
{
id: 2,
title: 'Buy c',
status: 0,
}
]
};
this.onTitleChange = this.onTitleChange.bind(this);
}
onTitleChange(id, title) {
console.log(id, title);
debugger
}
最佳答案
您可以使用展开运算符克隆状态对象,然后使用 findIndex
方法在数组中查找具有给定 id 的对象索引,修改对象并设置状态。
constructor(props) {
super(props);
this.state = {
data: [{
id: 0,
title: 'Buy a',
status: 0, // 0 = todo, 1 = done
},
{
id: 1,
title: 'Buy b',
status: 0,
},
{
id: 2,
title: 'Buy c',
status: 0,
}
]
};
this.onTitleChange = this.onTitleChange.bind(this);
}
onTitleChange(id, title) {
var data = [...this.state.data];
var index = data.findIndex(obj => obj.id === id);
data[index].title = title;
this.setState({data});
}
关于javascript - 如何使用 setState 更新对象数组中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45878147/