ReactJS:更新数组中数组对象的记录

时间:2020-07-06 11:41:46

标签: reactjs

我正在学习reactJS,我正在做一个练习示例,其中我必须更新产品及其数量。所需的最终输出格式如下:

productData = [
    name: '',
    code: '',
    Quantity:  [specificationName: "", quantity: ""]
]

我添加了在productData中添加记录的功能。但是我在更新数量数组时面临问题。而不是更新数据,而是在“数量”数组中添加一条新记录。我之所以不使用索引,是因为我已经读到,当我们的数据是非静态的时,这不是一个好方法。

下面是我的代码:

handleSubmit = (event) => {
   let productData = {};
   let specificationQuantity = [];

   const productForm = new FormData(event.target);

   for (var [key, value] of productForm.entries()) {
            
     if (key !== "name" && key !== "code" ){
              
       let updateQuantity = {
           specificationName: key,
           quantity: value
       }

       specificationQuantity.push(updateQuantity)
     }
            
    productData = {
      name: colorForm.get('name'),
      code: colorForm.get('code'),
      Quantity: specificationQuantity
    }
  }
  this.state.productData.push(productData)
}

比方说,加法后我有以下2条记录

  {
    code: "#0000C3",
    name: "Blue",
    Quantity: Array(2)
       0: {name: "", quantity: ""}     // this record is automatically created idk why
       1: {name: "v1", quantity: "1"}
  }
  {
    code: "#00001E",
    name: "Black",
    Quantity: Array(2)
       0: {name: "", quantity: ""}  
       1: {name: "v2", quantity: "2"}
  }

,当我尝试将“ v1”的数量更新为3时,只有蓝色中的数量应更新为{name:“ v1”,数量:“ 3”} 但我得到以下结果

{
    code: "#0000C3",
    name: "Blue",
    Quantity: Array(3)
       0: {name: "", quantity: ""}     // this record is automatically created idk why
       1: {name: "v1", quantity: "1"}
       2: {name: "v1", quantity: "3"}
  }
  {
    code: "#00001E",
    name: "Black",
    Quantity: Array(3)
       0: {name: "", quantity: ""}  
       1: {name: "v2", quantity: "2"}
       2: {name: "v1", quantity: "3"}
  }

1 个答案:

答案 0 :(得分:1)

问题出在这一行

this.state.productData.push(productData)

您实际上是在直接改变状态,这就是为什么您面临意外行为的原因。

请查看以下内容: https://reactjs.org/docs/state-and-lifecycle.html#using-state-correctly