【发布时间】:2019-07-11 14:27:25
【问题描述】:
在我的状态下,我想更新对象数组中第一项的对象属性。对象属性没有改变,即使我正在采取措施确保不变性。
this.state = {
myFruits: [{a: false, b: 2, c: 'apple'}, {'a': false, b: 4, c: 'kiwi'}, ...],
otherCategory: {}
}
/// further down the code in componentDidUpdate
{ myFruits } = this.state;
let copyFruits = [...myFruits];
let newFruit = { ...copyFruits[0], a : true };
// console.log(newFruit): {a: true, b: 2, c: 'apple'}
copyFruits[0] = newFruit;
// console.log(copyFruits[0)] = {a: true, b: 2, c: 'apple'}
this.setState({ myFruits: copyFruits });
// the end result is the same as the original state, where the first item, apple, has a : false instead of expected a : true
componentDidUpdate 中正在进行此更改,我不确定这是否有任何影响。
【问题讨论】:
标签: arrays reactjs object state