【问题标题】:Clone state in ReduxRedux 中的克隆状态
【发布时间】:2018-02-07 09:43:42
【问题描述】:

我的 Reactjs-Redux 应用程序中有这段代码

switch (action.type) {

    case SET_RISPOSTA:
    
                const newState = {...state}
                                newState.verifica.domande[action.indexDomanda].risposte[action.indexRisposta].valore = action.valore
                console.log(state.verifica.domande[0].risposte[0].valore)         console.log(newState.verifica.domande[0].risposte[0].valore)

            return newState

  default:

  return state

}

我希望控制台显示

未定义(未定义的值) 1(action.valore 的价值)

但控制台显示

1 1

即使我使用了 {...state},为什么我的状态对象发生了变异?

如果我放了

console.log(state.verifica.domande[0].risposte[0].valore)

之前

const newState = {...state}

控制台显示

未定义 1

【问题讨论】:

  • 这是我的第一个 Stack Overflow 问题!

标签: reactjs redux state


【解决方案1】:

因为const newState = {...state} 只创建了state 的新对象。它不会递归地创建新对象。这意味着在做{...state}之后,下面会有所不同

state !== newState // true

但以下将保持不变

`newState.verifica` === `state.verifica` // true

【讨论】:

  • 谢谢!我怀疑这就是原因。我是否也为 newState.verifica 为 state 做同样的事情?有没有最好的方法来做我想做的事情?
  • redux.js.org/docs/recipes/reducers/ImmutableUpdatePatterns.html 这里建议“复制所有级别的嵌套数据”以保持旧状态不变。
  • 是的,我的错。我在完全不同的背景下评论了这一点。删除了评论。感谢您指出这一点。
猜你喜欢
  • 2020-02-09
  • 1970-01-01
  • 2011-01-30
  • 2021-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-10
  • 2018-09-16
相关资源
最近更新 更多