我正在使用React,我的状态被定义为一个对象数组。 我需要能够改变state.data阵列只在一个特定的元素,例如ID对象1如何使用setState更新对象数组中的对象
我想知道:
- 什么是正确的方法如何使用
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
}
好的答案。只是想指出@Radex应该谨慎使用'setState':'onTitleChange'函数不应该被调用到组件正在更新的生命周期方法中(例如componentDidUpdate),因为否则它会导致无限循环。预先检查此文档条目https://facebook.github.io/react/docs/state-and-lifecycle.html – Fotis