https://github.com/immerjs/immer#supported-object-typesgit
immer 是用来作 immutable 的. es6
angular 的 change detech 机制, 有时候为了要性能好一些,咱们须要用 onPush 而后得配合 immutable 来让 input 触发. github
可是呢, immuable.js 写起来很丑, 原生 es6 得写法也很差看. 因而就有了 immer.性能
早前 immer 彻底不支持 class 因此我就没有用,最近看了一下发现部分支持了. 因此开始用了.ui
import { produce, immerable } from "immer"; class Product { constructor(data?: Partial<Product>) { Object.assign(this, data); } [immerable] = true; date: Date; colors: Color[]; private _price : number; public get price() : number { return this._price; } public set price(v : number) { this._price = v; } } class Color { constructor(data? : Partial<Color>) { Object.assign(this, data); } [immerable] = true; text: string } const product = new Product({ date: new Date(), price: 50, colors : [new Color({ text : 'dada' })] }); const newProduct = produce(product, next => { next.price = 10; }); console.log('instanceof Product', newProduct instanceof Product); console.log('is new', newProduct !== product); console.log('new value', newProduct.price === 10);
用法很简单. 调用, produce, 而后把对象传进去, next 是一个 proxy 对象, 咱们像通常得操做方式就能够了, 最后会返回新得对象. this
它并非 clone 整个子孙对象哦,而是你有修改才会 clone. spa
若是是 class 要加上一个 symbol [immerable] = trueprototype
不支持的地方不少要特别注意哦 :指针
1. 若是要修改 Date 的, 必须本身 clone 一个新的. code
2. array 只能够修改 length 不能够本身添加额外的属性.
3. prototype 是不会 clone 的, 保留本来指针
4. Built-in classes like Map
and Set 不支持 (官网给了 workaround, 我也没用, 因此暂时无论)
5. 不支持 computed property (若是是通常写 getter setter 是能够的, 由于 getter setter 实际上是 define 到了 prototype 上而不是对象上面, 若是你要 define 到对象上, 那 immer 就支持不到了)