在减速器中改变状态的后果是什么? [英] What are the consequences of mutating state in a reducer?
问题描述
redux 指南指出:
The redux guide states:
我们不会改变状态.我们使用 Object.assign() 创建一个副本.Object.assign(state, { visibleFilter: action.filter }) 也是错误的:它会改变第一个参数.您必须提供一个空对象作为第一个参数.您还可以启用对象扩展运算符建议,改为编写 { ...state, ...newState }.
We don't mutate the state. We create a copy with Object.assign(). Object.assign(state, { visibilityFilter: action.filter }) is also wrong: it will mutate the first argument. You must supply an empty object as the first parameter. You can also enable the object spread operator proposal to write { ...state, ...newState } instead.
我碰巧发现自己正在编写以下工作代码片段:
I happened to catch myself writing the following snippet of working code:
[actions.setSelection](state, {payload}) {
state[payload.key] = payload.value;
return state;
},
我对此有一种不好的感觉,并重新阅读了智慧指南.我已经把它改写成这样:
I had a bad vibe about it, and revisited the guide for wisdom. I have since rewritten it as this:
[actions.setSelection](state, {payload}) {
const result = Object.assign({}, state);
result[payload.key] = payload.value;
return result;
},
我很确定我在代码中的其他地方冒犯了上面提到的诫命.如果我不努力追踪他们,我会看到什么样的后果?
I am fairly sure I have offended the commandment noted above elsewhere in my code. What kind of consequence am I looking at for not tracking them down with diligence?
(注意:上面的 reducer 语法是通过 redux-actions 实现的.否则它会是 reducer fn switch/case 中的代码块.)
(Note: The reducer syntax above is via redux-actions. It would otherwise be the block of code in a reducer fn switch/case.)
推荐答案
Mutating state 是 React 中的一种反模式.React 使用的渲染引擎依赖于状态变化是可观察的这一事实.这种观察是通过比较前一个状态和下一个状态来进行的.它将用差异更改虚拟 dom,并将更改的元素写回 dom.
Mutating state is an anti-pattern in React. React uses a rendering engine which depends on the fact that state changes are observable. This observation is made by comparing previous state with next state. It will alter a virtual dom with the differences and write changed elements back to the dom.
当你改变内部状态时,React 不知道改变了什么,甚至更糟;当前状态的概念是不正确的.因此 dom 和虚拟 dom 将变得不同步.
When you alter the internal state, React does not know what's changed, and even worse; it's notion of the current state is incorrect. So the dom and virtual dom will become out of sync.
Redux 使用相同的想法来更新它的 store;一个 action 可以被 reducers 观察到,它计算 store 的下一个状态.更改被发出,例如被 react-redux connect
消耗.
Redux uses the same idea to update it's store; an action can be observed by reducers which calculate the next state of the store. Changes are emitted and for example consumed by react-redux connect
.
简而言之:永远不要改变状态.您可以使用第 3 阶段传播语法代替 Object.assign:
So in short: never ever, mutate state. Instead of Object.assign you can use the stage-3 spread syntax:
{...previousState,...changes}
另外请注意,这也适用于数组!
Also please note, this is true for arrays as well!
这篇关于在减速器中改变状态的后果是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!