在 Redux 中重写状态 [英] Rewriting state in Redux
问题描述
在 redux 中,我知道状态是不可变的,当您创建新状态时,您实际上是在使用新信息更新对象,然后完全重写状态.
In redux I understand that state is immutable and when you create new state you are essentially updating the object with what ever new information there is and then totally rewriting the state.
今天我有一个想法,我不确定它有多愚蠢.
Today I had a thought and I am not sure how stupid it is.
不断重写状态在计算上是否昂贵?我知道这是 Redux 的主要范式之一,但我想知道从内存和空间的角度来看这是否有意义.
Is it computationally expensive to keep re-writing the state? I know that this is one of the major paradigms of Redux, but I want to know if this makes sense from a memory and space perspective.
推荐答案
你可以在 Redux 中改变状态,但你不应该不惜任何代价这样做,因为你会在 Redux 反模式
You are allowed to mutate the state in Redux but you should not do it at any cost because you'd be coding in Redux anti-patterns
改变对象,在原生 JavaScript 或任何框架中,可能会带来许多副作用,调试起来可能会非常痛苦.您应该选择 纯函数 除非有必要进行变异.
Mutating objects, in vanilla JavaScript or in any framework, may bring many side-effects with it which could be very painful to debug. You should opt for pure functions unless its necessary to mutate.
现在回到 Redux,reducer 中的函数应该是纯函数.原因如下:
Now back to Redux, functions in reducers should be pure functions. here is why:
Redux 算法检查如果通过比较前一状态和下一状态的内存位置来更新状态.
Redux algorithm checks if a state has been updated by comparing the memory location of the previous and the next state.
现在,当您在 JavaScript 中改变对象时,您只是在更新现有对象,因此,内存位置保持不变,存储不会更新.改变状态还会禁用 Redux devtools 的一项基本功能,即时间旅行以进行调试.
Now, when you mutate an object in JavaScript, you are simply updating an existing object and therefore, the memory location remains the same and the store does not get updated. Mutating the state also disables an essential feature of Redux devtools, time-travelling to debug.
另一方面,如果不是改变对象而是创建一个新对象,当 redux 比较 previousState(更改之前的状态)和 nextState(您发送的新状态)的内存位置时,Redux 在此时意识到发生了变化,它会用您的最新状态更新商店.
On the other side, if instead of mutating the object you create a new one, when redux compares the memory location of previousState (the state before you changed it) and the nextState(the new one which you sent), Redux at this point realises that there has been a change and it updates the store with you latest state.
参考:
impure functions and issues with Redux devtools:
https://github.com/coodoo/react-redux-isomorphic-example/commit/6998c46d3c1a102b5f1bfb4f9aa44e5e7f9f6e87#commitcomment-12457617
为什么 Redux 需要 reducers 成为纯函数"
https://medium.freecodecamp.org/为什么-redux-needs-to-be-pure-functions-d438c58ae468
Why Redux need reducers to be "pure functions"
https://medium.freecodecamp.org/why-redux-needs-reducers-to-be-pure-functions-d438c58ae468
Redux 开发工具:https://github.com/gaearon/redux-devtools一个>
Redux devtools: https://github.com/gaearon/redux-devtools
这篇关于在 Redux 中重写状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!