2017-11-10 123 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

相关问题