2017-11-10 124 views
1

我正在查看example application provided by NgRx的代碼。我注意到示例應用程序中的每個reducer函數都有一個返回值,該值由該特定reducer的State接口鍵入。例如,書籍減速機具有下面的代碼:State vs ActionReducer <State> as NgRx reducer返回類型

export interface State { 
    ids: string[]; 
    entities: { [id: string]: Book }; 
    selectedBookId: string | null; 
} 

export const initialState: State = { 
    ids: [], 
    entities: {}, 
    selectedBookId: null, 
}; 

export function reducer(
    state = initialState, 
    action: book.Actions | collection.Actions 
): State { 

後來,我正在讀一本關於NGRX由奧倫Farhi題爲Reactive Programming with Angular and NgRx,和整個的代碼片段來呈現出減速功能的常見車身結構( 。第24-25頁)爲共同的結構的代碼顯示減速函數的返回值作爲由ActionReducer正在鍵入與State作爲類型參數(在這種情況下稱爲SomeInterface而非State):

export interface SomeInterface { 
    items: Item[], 
    filter: string 
} 

let initialState: SomeInterface = { 
    items: [], 
    filter: '' 
} 

export function MyReducer (
    state: SomeInterface = initialState, 
    action: Action 
): ActionReducer<SomeInterface> { 

爲什麼一個代碼示例使用狀態和其他u將ActionReducer與State作爲Reducer函數的返回值的類型參數?爲什麼會選擇其中一個功能簽名?每個服務的目的是什麼?

本書是爲NgRx 2.2.1編寫的,而示例應用程序是針對最新版本的NgRx(版本4.1.1)。我猜測返回類型的區別不能簡單地由NgRx的差異來解釋版本,因爲最新版本的NgRx也有ActionReducer。

謝謝!

+0

使用此[* *中博客**](https://medium.com/@aravindfz/setting-up-storemodule-in-ngrx-4-0-b7c60732aa64)設置爲ngrx-4.0 – Aravind

回答

2

ActionReducer是其進口過程中傳遞給StoreModule減速的集合

  • 減速應該總是(在你的情況SomeInterface)返回初始狀態類型

    export interface SomeInterface{ 
        .... 
    } 
    const initialState: SomeInterface= { 
        .... 
    }; 
    export function reducer(state = initialState, action: Actions): SomeInterface{...} 
    
  • ActionReducer應該是一個減速器集合,它需要一個類型接口,它將是一個應用程序的PP商店界面,這是集合稱爲減速機廠

    export const reducers: ActionReducerMap<AppStore> = { 
         someInterfacerSlice: someInterface.reducer, 
    }; 
    
  • 定義一個全局應用商店界面,如下模塊,

    export interface AppStore { 
         someInterfaceSlice: SomeInterface; 
         stateSlice: StateSlice; 
    } 
    
+0

那麼,你是說這本書「使用Angular和NgRx進行反應式編程」在其代碼中存在錯誤,而且應該如此有SomeInterface而不是ActionReducer 作爲reducer的返回類型? – user2245766

+0

我沒明白 – Aravind

+0

@ user2245766 upvote too :) – Aravind

相關問題