如何使用扩展运算符/ES6 实现此目的?
我想遍历我的数据并用一个对象数组填充我的状态,其中对象包含两个键/值对。我希望它像...
this.state = {
data: [ {indexNumber: 1, show: false}, {indexNumber: 2, show: false}, {indexNumber: 3, show: false} ]
我的[变异]版本;
this.state = { data: []}
data.map((element, index) => {
this.state.data.push({ indexNumber: index, show: false}] })
});
最佳答案
您不能修改状态对象。您将必须调用 setState 并使用新值:
this.setState({data: [...this.state.data, {indexNumber: index, show: false}]})
关于javascript - 在 react 中使用 setState 将预定义对象插入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52081714/