Reactjs 如果使用扩展运算符,为什么状态会发生变化?
我在JSFIDLE上测试了这段代码Reactjs 如果使用扩展运算符,为什么状态会发生变化?,reactjs,state,Reactjs,State,我在JSFIDLE上测试了这段代码 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(thi
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})
};
然而,即使我没有设置状态,控制台日志显示每次单击加号和减号时状态都会发生变化
我做了与本文相同的事情
据我所知
这不是另一个问题的重复,我不是在要求一种有效的方法,正如@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;
正如@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;
正如注释中提到的@Carcigenicate,使用spread操作符创建数组的浅拷贝。这会给您带来问题,因为数组的扩展版本包含通过引用传递的对象。因此,即使局部变量产品是this.state.products的新副本,它们都包含对相同对象的引用 要实现您试图执行的操作,您必须克隆this.state.products中的对象。一种可能的方法是使用Object.assign并将const products=[…this.state.products]替换为:
正如注释中提到的@Carcigenicate,使用spread操作符创建数组的浅拷贝。这会给您带来问题,因为数组的扩展版本包含通过引用传递的对象。因此,即使局部变量产品是this.state.products的新副本,它们都包含对相同对象的引用 要实现您试图执行的操作,您必须克隆this.state.products中的对象。一种可能的方法是使用Object.assign并将const products=[…this.state.products]替换为:
这是列表结构的一个浅显副本。它不会复制它所包含的元素。您需要以某种方式复制它们。可能的副本是列表结构的浅副本。它不会复制它所包含的元素。你需要把它们复印一下。可能是复印件。谢谢。我现在明白了,谢谢。我现在明白了
const products = [
Object.assign({}, this.state.products.Orange),
Object.assign({}, this.state.products.Apples),
Object.assign({}, this.state.products.Bananas)
]