Immutable Updates in React and Redux
React和Redux中的不可变更新
How do you update state when you are not allowed to change it?
当不允许改变时如何更新状态?
Immutability is kind of hard to wrap your head around at first. It seems like a paradox. Changing the data without changing the data? Huh?
当刚开始学习不可变特性的时候是很难理解的,就像一个悖论:不允许改变数据而改变数据?
On top of that, writing code to do immutable state updates is tricky. Below, you will find a few common patterns.
Try them out on your own, whether in the browser developer console or in a real app. Pay particular attention to the nested object updates, and practice those. I find those to be the trickiest.
All of this actually applies to React state too, so the things you learn in this guide will apply whether you use Redux or not.
Finally, I should mention that some of this code can become easier to write by using a library like Immutable.js, though it comes with its own tradeoffs. If you recoil at the syntax below, check out Immutable.js.