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

标签 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)
        }

      }

最佳答案

这是与在 javascript 中使用扩展运算符时变量浅复制有关的问题。和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)

希望有帮助。如有任何疑问/困惑,请返回。

关于reactjs - 更新一个状态变量更改另一状态变量中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55547534/

相关文章:

javascript - React-Router-Dom `Link` 更改路由,但没有组件加载

reactjs - 如何确保reactjs状态更新,然后调用函数?

android - 按下按钮后改变按钮的外观?

haskell - 我可以使用状态 monad 模拟交互式程序吗?

javascript - react : why the tasks doesn't appear?

unit-testing - 测试自定义 redux 中间件

javascript - react 组件与箭头函数奇怪的行为

css - Reactjs Bootstrap 覆盖 CSS

kotlin - 如何在函数式编程中处理私有(private)状态?

css - 有没有更好的将 CSS 从 CDN 包含或导入 CRA 应用程序而不弹出