如果我使用传播运算符,为什么状态会发生变化? [英] Why is the state mutating if I am using spread operator?

查看:115
本文介绍了如果我使用传播运算符,为什么状态会发生变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有正在jsfiddle上测试的这段代码

I have this code that I am testing on 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/

但是,即使我没有设置状态",控制台日志也会显示每次单击加号和减号时状态都会改变.

However, even though I am not setting State, the console log shows that the state is changes every time I click on the plus and minus signs.

我所做的与本文据我了解

(这不是另一个问题的重复,我不是在寻求有效的方法)

(it is not duplicate of the other question, I am not asking for an efficient way)

推荐答案

如@Carcigenicate所述,您已经创建了数组的浅表副本,这意味着您有一个指向原始对象中相同对象的新数组.

As @Carcigenicate mentioned, you have created a shallow copy of the array which means you have a new array pointing to the same objects in the original.

为避免变异原始对象,您还需要创建一个您想要变异的对象的副本,例如:

To avoid mutating the original object, you will need to also create a copy of the one you would like to mutate, e.g.:

// 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;

这篇关于如果我使用传播运算符,为什么状态会发生变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆