2017-05-30 68 views
0

我一直在閱讀的東西在REDX一段時間。對我而言,這是一件奇怪的事情。在大多數人給出的例子中,所有的複製邏輯都是通過reducer來處理的。 我正在使用打字稿,並希望採用更多基於類的方法。但也許我錯過了一些東西。克隆,然後mutatate方法在減少

比方說,我有一個購物車類。隨着購物車減速器和購物車行動。 它看起來方式如下:

export class Cart 
{ 
    private items:{[key:string]:number} = {}; 

    constructor(items:{[key:string]:number} = {}) 
    { 
     Object.assign(this.items, items); 
    } 

    public addItem(id:string) 
    { 
     this.items[id] = this.items[id]?this.items[id]+1:1; 
    } 

    public removeItem(id:string) 
    { 
     this.items[id]--; 

     if(this.items[id] <= 0) 
     { 
      delete this.items[id]; 
     } 

    } 

    public setItemsCount(id:string, count:number) 
    { 
     this.items[id] = count; 
    } 

    public clone():Cart 
    { 
     return new Cart(Object.assign({}, this.items)); 
    } 

} 

所以,在這裏我incapsulating一類克隆邏輯。

在我減速器我會簽名去:

function reducer(state = new Cart(), action:Action): Cart { 
    //first clone, then mutate, then return 
} 

或者說,實際上,如何通過一個通用的方法只是深克隆的對象,那麼他們變異,然後返回?這種方法有什麼不好?

+0

爲什麼不加一個'Cart'類的方法,它從你的動作中獲取一個更新,並根據它的現有值和更新返回一個新的'Cart'實例? – adrice727

回答

3

由於幾個原因,這被認爲是不好的做法。

首先,不鼓勵類實例處於狀態because it will break time-travel debugging。你可以這樣做,但它不是「正確」的方式。

其次,你的班級直接改變其內容。這也會打破時間旅行調試,並且result in your connected React components not re-rendering properly

第三,Redux鼓勵更多的功能性方法,而不是OOP。

您可能希望通過我的兩個最近的博客文章,The Tao of Redux, Part 1 - Implementation and IntentThe Tao of Redux, Part 2 - Practice and Philosophy,它進入細節上讀什麼技術限制Redux的需要,爲什麼,爲什麼常見的做法,使用終極版存在的,爲什麼其他方法可能可能但不被認爲是慣用的。

1

你可能會這樣。畢竟......你會尊重Redux架構所需的不變契約。

但我不建議你這樣做。

深層克隆根本就不表現。您的商店越大,您的應用程序越慢。

另外,要honnest我試過這種方法有classhttps://github.com/maxime1992/pizza-sync/blob/5212a29ee9be916383f759a3a129f7b580ed32ea/frontend/src/app/shared/state/orders/orders.reducer.ts

而且它不是那麼糟糕。但我最終使用了一個簡單的函數。

有一件事,你的actions在這裏不會輸入,所以你會失去Typescript的一些好處。

而是這樣做的,你應該創建一個class每個動作,在這次談話https://www.youtube.com/watch?v=cyaAhXHhxgk

也解釋了,我已經做了一個NGRX啓動,可能會幫助您入門:https://github.com/maxime1992/angular-ngrx-starter

+0

根據@markerikson的評論,只有一件事需要澄清:我沒有使用過一個班級作爲直接減速器,而我所有的方法都是靜態的,所以在我的情況下,時間旅行並沒有打破,這與您的情況略有不同 – Maxime