我有正在jsfiddle上测试的这段代码
onVote = (dir, index) => {
console.log(this.state)
const products = [...this.state.products]
products[index].votes = dir ? products[index].votes + 1 : products[index].votes - 1
console.log(this.state.products[index].votes)
// this.setState({products})
};
https://jsfiddle.net/hkL3wug7/2/
但是,即使我未设置“状态”,控制台日志也显示每次单击加号和减号时状态都会更改。
const newState = [...state] // clone the array
newState[action.index].done = true
return newState
据我所理解
(这不是其他问题的重复,我不是在寻求有效的方法)
正如@Carcigenicate提到的,您已经创建了数组的浅表副本,这意味着您有一个指向原始对象中相同对象的新数组。
为了避免变异原始对象,您还需要创建一个您想要变异的对象的副本,例如:
// Shallow copy of the array
const products = [...this.state.products];
// Shallow copy of the object within the array
const updatedProduct = { ...products[index] };
// Update the copy of the object
updatedProduct.votes = dir ? updatedProduct.votes + 1 : updatedProduct.votes - 1;
// Replace the object with the updated copy
products[index] = updatedProduct;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句