首页 > 解决方案 > ReactJS 不保存对象

问题描述

我目前在 React 中遇到一个奇怪的问题,即数组中更改的对象无法保存。

changeQuantity(Product, Quantity) {
    let index = this.state.products.findIndex(p => p === Product);
    Product.Amount = Quantity;

    let productarray = this.state.products;

    productarray[index] = Product;

    console.log(index);
    console.log(productarray[index]);
    console.log(productarray);

    this.setState({
      products: productarray
    })

  }

index= 0

productarray[index]= 有正确的Amount

productarray= 有错误Amount(仍然为零,无论我输入哪个数字Quantity

关于为什么它不能正确保存,我在这里有什么遗漏吗?

标签: javascriptarraysreactjs

解决方案


尝试创建一个新数组,这就是 react 判断对象是否更改的方式。

  oldArray[index] = anotherObject
  const newArray = [...oldArray]
  setState{ products: newArray }

推荐阅读