更新一个状态变量以更改另一状态变量中的数据

时间:2019-04-06 09:08:39

标签: reactjs state

我要在两个状态变量中设置来自api的数据,两个值都相同。但是当我更新一个状态变量时,另一个状态变量也会改变。

       Api.get("url")
          .then((response) => {
            this.setState(
              {
                deliveryInfoSection2: Object.assign({}, response.data),
                deliveryInfoSection2copy: Object.assign({}, response.data),
              }
            );

          })



    updateState() {
        try {
          newVal = { ...this.state.deliveryInfoSection2 };
          newVal.orderDetails[index].bo = value.replace(global.REG_NUMBER_ONLY, '');

    //After this state variable deliveryInfoSection2copy is also updating.
          this.setState({ deliveryInfoSection2: newVal }, () => {
            if (this.state.deliveryInfoSection2.orderDetails[index].bo != '') {

        }
        catch (e) {
          alert("error" + e)
        }

      }

1 个答案:

答案 0 :(得分:1)

这是关于JavaScript中的shallow copy of variables while using spread operator的问题。它与react的setState没有关系。传播算子为对象创建一个浅表副本。

response = {
    orderDetails: [
        {
           bo: "tempData1"
        },
        {
           bo: "tempData2"
        }
    ]	
}
deliveryInfoSection2 = Object.assign({}, response)
deliveryInfoSection2Copy = Object.assign({}, response)

//Here spread operator will create shallow copy and so, the references are copied and hence any update to one will update other.
newVar = { ...deliveryInfoSection2 }
newVar.orderDetails[0].bo = "newValue"
deliveryInfoSection2 = newVar
console.log("deliveryInfoSection2", deliveryInfoSection2)
console.log("deliveryInfoSection2Copy", deliveryInfoSection2Copy)

要解决此问题,您需要创建对象的深层副本。
您可以使用JSON.parse(JSON.stringify(object))

response = {
    orderDetails: [
        {
            bo: "tempData1"
        },
        {
            bo: "tempData2"
        }
    ]	
}
deliveryInfoSection2 = Object.assign({}, response)
deliveryInfoSection2Copy = Object.assign({}, response)

//This will create a deep copy for the variable
newVar = JSON.parse(JSON.stringify(deliveryInfoSection2))
newVar.orderDetails[0].bo = "newValue"
deliveryInfoSection2 = newVar
console.log("deliveryInfoSection2", deliveryInfoSection2)
console.log("deliveryInfoSection2Copy", deliveryInfoSection2Copy)

希望有帮助。恢复任何疑问/困惑。