Redux 中的只读状态

Read only state in Redux

在 Redux 文档中,解释得很清楚:
改变状态的唯一方法是发出一个动作。
事实上,这是一个非常好的原则,但似乎可以做到这一点:

const render = () => {
 document.getElementById("container").innerHTML = "state : " + JSON.stringify(myStore.getState())
  myStore.getState().form.subobj.ssub.key2 = "ha ha";
};

Full code here

为什么 redux 不能防止外部突变?
我们如何确保开发人员永远不会这样做?

来自Redux的源代码:

   var finalState = mapValues(finalReducers, (reducer, key) => {
      var previousStateForKey = state[key]
      var nextStateForKey = reducer(previousStateForKey, action)
      if (typeof nextStateForKey === 'undefined') {
        var errorMessage = getUndefinedStateErrorMessage(key, action)
        throw new Error(errorMessage)
      }
      hasChanged = hasChanged || nextStateForKey !== previousStateForKey
      return nextStateForKey
    })

Redux combineReducers 将状态对象视为普通 JavaScript 对象

您必须将 immutablejs 之类的东西与 redux 一起使用才能达到您想要的效果。

对象的不变性不是 Redux 的工作。

Redux 是 JavaScript 应用程序的可预测状态容器。

要使用不可变对象,您可以考虑使用 Immutable.jsdot-prop-immutable