Angular 學習筆記 immer 使用

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 就支持不到了)

相關文章
相關標籤/搜索