随着单页面 JavaScript 应用越来越复杂,以可预测的方式进行状态管理就显得愈发重要。不可变性(Immutability)可以帮我们确保应用具有一致的表现,不幸的是,JavaScript 没有提供内置的具有深层不变性的数据结构(参见 ES 记录与元组提案)。Immer(在德语中是永远的意思)是一个极小的包,它可以让你用更加便利的方式处理不可变状态。它基于写时复制(copy-on-write)机制进行工作,具有最小化的 API,而且只操作普通的 JavaScript 对象和数组。这意味着其数据访问是无缝的,不需要做大规模重构就能把不可变性引入到现有代码库中。目前,我们的很多团队都在自己的 JavaScript 代码库中使用它,相对于 Immutable.js,我们更喜欢它一些,这就是把它移入“试验”中的原因。
With the increasing complexity of single-page JavaScript applications, managing state predictably is becoming more and more important. Immutability can help to ensure our applications behave consistently, but unfortunately JavaScript doesn't natively support the ability to create immutable objects. Libraries such as Immutable.js filled that gap but introduced new problems because now two kinds of objects and arrays existed in the application, the library's version and the native JavaScript ones. Immer — German for always — is a tiny package that lets you work with immutable state in a more convenient way. It's based on the copy-on-write mechanism, has a minimal API and operates on normal JavaScript objects and arrays. This means that data access is seamless and no large refactoring efforts are needed when introducing immutability to an existing codebase.