如果我使用传播运算符,为什么状态会发生变化?

用户名

我有正在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/

但是,即使我未设置“状态”,控制台日志也显示每次单击加号和减号时状态都会更改。

我所做的与本文中的相同https://medium.com/@giltayar/immutably-setting-a-value-in-a-js-array-or-how-an-array-is-also-an-object -55337f4d6702

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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

为什么在使用React Redux过滤时我的原始状态会发生变化

为什么在应用算术运算时我的“dtype”会发生变化?

Tensorflow:如果对同一输入执行多个独立操作,则运算符结果会发生变化

为什么当我使用动画时项目的位置会发生变化?

为什么我的玩家的移动速度会发生变化?(在 Unity 中使用渔网)

当我在反应中设置其他对象的状态时,为什么我的数组值会发生变化?

为什么遍历方阵时会发生变化?

为什么[0]会发生变化?

为什么“to”道具在点击时会发生变化?

为什么索引值会发生变化?

为什么当我转换为 ndarray 时我的日期列会发生变化

为什么当我分别使用“ if”语句和在“ if”中使用“ if”时值会发生变化?

尝试使用格式运算符创建变量,但变量的数据发生变化

为什么我的按钮使用 React-icon 组件时返回值会发生变化?

为什么上传照片时我的 gui 布局会发生变化?

为什么我的变量被调用时会发生变化?

为什么在Java中调用setTimeout函数之前,我的值会发生变化?

为什么当我将其设为链接时,文本的位置会发生变化?

为什么滚动后我的单元格中的图标会发生变化?

为什么我移动时游戏中的事物会发生变化?Java处理环境

为什么在运行“插入”函数后我的数字变量会发生变化?

为什么我的CSS宽度%在某些页面上会发生变化?

为什么我的for循环(python)在4次迭代后会发生变化?

为什么在我的代码运行时unsortedArray会发生变化?

为什么我的图像写成 jpg 文件后颜色会发生变化?

为什么我重新安装时代码块设置会发生变化?

Python:为什么使用 b = list(a) 复制列表后 id 会发生变化

为什么使用tkinter文本时光标的粗细会发生变化?

为什么使用生成器时const的值会发生变化?