【问题标题】:Why can't modify the nestState directly?为什么不能直接修改nestState?
【发布时间】:2017-01-09 05:14:25
【问题描述】:

在redux docs 我看到了这个:

常见错误 #1:指向相同对象的新变量

定义新变量不会创建新的实际对象 - 它只会创建对同一对象的另一个引用。此错误的一个示例是:

function updateNestedState(state, action) {
    let nestedState = state.nestedState;

    // ERROR: this directly modifies the existing object reference - don't do this!
    nestedState.nestedField = action.data;

    return {
        ...state,
        nestedState
    };
}

这个函数确实正确地返回了顶层状态对象的浅拷贝,但是因为nestedState变量仍然指向现有对象,所以状态被直接改变了。

但是我们知道combineReducers只是通过顶级引用来判断状态变化。见reduxcomBindReducer.js src:

let hasChanged = false
const nextState = {}

for (let i = 0; i < finalReducerKeys.length; i++) {
  const key = finalReducerKeys[i]
  const reducer = finalReducers[key]
  const previousStateForKey = state[key]
  const nextStateForKey = reducer(previousStateForKey, action)

  if (typeof nextStateForKey === 'undefined') {
    const errorMessage = getUndefinedStateErrorMessage(key, action)
    throw new Error(errorMessage)
  }

  nextState[key] = nextStateForKey
  hasChanged = hasChanged || nextStateForKey !== previousStateForKey
}

return hasChanged ? nextState : state

它只是访问每个reducer并判断状态引用是否改变。

所以回到问题,返回的对象引用发生了变化,所以hasChanged变量为真,redux工作正常。所以我不知道state的副作用是什么?

如果你知道,请告诉我,谢谢。

【问题讨论】:

    标签: reactjs redux react-redux


    【解决方案1】:

    我认为该示例与cobmineReducers 没有直接关系。我相信它试图提出与不变性相关的警告:每当复杂对象中的值发生变化时,整个层次结构都应该表明这一点。因此,如果state.nestedState.nestedField 发生变化,则意味着state.nestedState 发生了变化,state 也发生了变化。看看state 或nestedState 就足以意识到nestedField 已经改变了。
    不熟悉这个概念的开发人员可能经常认为将state.nestedState 分配给一个新变量然后更改它是可以的,但事实并非如此,因为a === state.nestedState 仍然是true。

    combineReducers 只关心其中一个切片是否已更改。如果遵循上述规则,它将“正常工作”。但是如果我们直接看state.nestedState 会发生什么?引用还是一样的,所以它不再起作用了。

    对于 React,connect 的工作方式相同。它对 props 进行浅层比较,依赖于相同的规则:不需要进行深层比较,因为父项应该指出子项是否发生了变化。

    回到你的问题:直接改变状态有什么副作用?
    让我们用你的例子:

    // reducer.js
    function reducer(state, action) {
       let nestedState = state.nestedState;
       nestedState.nestedField = action.data;
       return {
           ...state,
           nestedState
       };
    }
    

    这样可以正常工作:

    connect(state => ({ state }))(MyComponent)
    

    这不会:

    connect(state => ({ nestedState: state.nestedState }))(MyComponent)
    

    我希望它回答了你的问题,或者至少能对此有所了解。

    【讨论】:

    • 作为那个 Redux 文档页面的作者:是的,这就是我的意思。如果nestedState字段直接变异而不是换出,然后一个mapState函数返回那个nestedState值,connect会看到引用和之前一样,认为什么都没有改变,而不是实际重新渲染组件。
    • @OB3 感谢您的回复,从 react-redux 的角度我不认为它。现在我明白了。
    猜你喜欢
    • 2021-05-26
    • 1970-01-01
    • 1970-01-01
    • 2014-11-25
    • 1970-01-01
    相关资源
    最近更新 更多