Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
ReactJS:更新数组中数组对象的记录_Reactjs - Fatal编程技术网

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

ReactJS:更新数组中数组对象的记录,reactjs,Reactjs,我在学习reactJS,我在做一个实践例子,我必须更新一个产品及其数量。最终输出要求采用以下形式: productData = [ name: '', code: '', Quantity: [specificationName: "", quantity: ""] ] 我添加了在productData中添加记录的功能。但我在更新数量数组时遇到了问题。不更新数据,而是在数量数组中添加新记录。我没有使用索引,因为我已经读到,当我们

我在学习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',quantity:'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"}
  }

问题就在这方面

this.state.productData.push(productData)
你实际上是在直接改变状态,这就是为什么你会面临意想不到的行为

请看一下这个:

@Tushar是对的。仅使用
this.setState({})
修改状态values@OnerT. 我试过了,但它仍然在更新中添加了一条新记录。我已将其更改为。setState({productData:productData})但它仍然在更新中添加了一行。您能否创建一支笔并共享链接,以便我们可以更好地了解发生了什么?