【问题标题】:React Js: Not able to reset nested stateReact Js:无法重置嵌套状态
【发布时间】:2019-12-06 07:59:07
【问题描述】:

我无法在反应中重置状态

例子

let initialState = {a:1, b:{c: 2, d: 4}, e:{f:6, g:7}}

constructor(){
this.state = initialState;
this.baseState = this.state;//set the initial state in the base state
}

//然后假设我将状态修改为 e.f: 10 和 b.c.:10; //状态更新

//然后我再次尝试将状态重置为初始状态

this.setSate({...this.baseSate});

它会修改未嵌套的元素,即它会修改元素'a',但不会修改嵌套元素'b.c'

【问题讨论】:

  • 嗨 Niks,检查我的解决方案,如果有帮助,请告诉我。

标签: reactjs react-state-management react-state


【解决方案1】:

你应该使用函数式setState

this.setState(prevState => ({
   ...prevState,
   ...this.baseState
}), () => console.log(this.state, this.baseState));

Demo

【讨论】:

  • 我发现,我基本上是从不同的文件中导入初始状态,所以实际发生的情况是在执行 'this.state = initialState' 时,它会复制数据以及地址位置,并更新状态和初始状态对象中的数据
【解决方案2】:

您做错的是将this.state 的引用设置为this.baseState。 因此,您对状态所做的任何更改本质上也会反映在基本状态中,因为它们具有相同的引用,即都引用内存中的相同内存空间。

下面的代码应该可以解决你的问题。

let initialState = {a:1, b:{c: 2, d: 4}, e:{f:6, g:7}}

constructor(){
this.state = {...initialState};
this.baseState = {...this.state};//set the initial state in the base state
}

【讨论】:

    【解决方案3】:

    你需要使用深度应对对象

    let initialState = {a:1, b:{c: 2, d: 4}, e:{f:6, g:7}}
    
    constructor(){
    this.state = JSON.parse(JSON.stringify(initialState));
    this.baseState = JSON.parse(JSON.stringify(initialState));//set the initial state in the base state
    }
    

    Reference Link

    【讨论】:

      猜你喜欢
      • 2021-09-03
      • 1970-01-01
      • 1970-01-01
      • 2018-08-30
      • 1970-01-01
      • 2021-04-27
      • 1970-01-01
      • 1970-01-01
      • 2018-08-17
      相关资源
      最近更新 更多