问题描述
我正在学习 redux 并且正在努力理解为什么状态必须是不可变的.你能不能给我提供一个例子,最好是在代码中,破坏不可变契约会导致不那么明显的副作用.
I'm learning redux and am struggling to understand why state has to be immutable. Could you provide me with an example, in code preferably, where breaking the immutable contract results in an not so obvious side effect.
推荐答案
Redux 最初的发明是为了展示时间旅行调试"的想法——能够来回遍历已调度操作的历史,看看会发生什么每个步骤的用户界面看起来都像.另一方面是能够实时编辑代码,重新加载它,并查看给定新的 reducer 逻辑的输出是什么样的.
Redux was originally invented to demonstrate the idea of "time-travel debugging" - being able to step back and forth through the history of dispatched actions, and see what the UI looks like at each step. Another aspect is being able to live-edit the code, reload it, and see what the output looks like given the new reducer logic.
为了能够正确地在状态之间来回切换,我们需要确保 reducer 函数没有副作用.这意味着数据更新需要一成不变地应用.如果reducer 函数实际上直接修改了它的数据,那么在状态之间来回切换将导致应用程序以意想不到的方式运行,调试工作将被浪费.
In order to be able to properly step back and forth between states, we need to make sure that reducer functions have no side effects. That means data updates need to be applied immutably. If a reducer function actually directly modifies its data, then stepping back and forth between states will cause the application to behave in an unexpected fashion, and the debugging effort will be wasted.
此外,React-Redux 库依赖浅层相等性检查来查看组件的传入数据是否已更改.如果数据引用相同,则 connect
生成的包装组件假定数据没有改变,并且组件不需要重新渲染.不可变数据更新意味着创建了新的对象引用,因此 connect
将看到数据已更改并且 UI 需要更新.
Also, the React-Redux library relies on shallow equality checks to see if the incoming data for a component has changed. If the data references are the same, then the wrapper components generated by connect
assume that the data has not changed, and that the component does not need to re-render. Immutable data updates means that new object references are created, and thus connect
will see that the data has changed and the UI needs to update.
这篇关于为什么使用 redux 保持不可变状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!