Rad*_*dex 2 javascript ecmascript-6 reactjs
我正在使用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
}Run Code Online (Sandbox Code Playgroud)
您可以使用传播运算符克隆状态对象,然后使用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});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2621 次 |
| 最近记录: |