1

我正在查看NgRx 提供的示例应用程序的代码。我注意到示例应用程序中的每个reducer 函数都有一个返回值,该值由该State特定reducer 的接口键入。例如,books 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 {

后来,我在阅读 Oren Farhi 的一本关于 NgRx 的书,名为Reactive Programming with Angular 和 NgRx,偶然发现了一段代码片段,显示了 reducer 函数的通用主体结构(第 24-25 页)。通用结构的代码将 reducer 函数的返回值显示为由ActionReducerwithState作为类型参数输入(在这种情况下调用SomeInterface而不是调用):State

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

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

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

为什么一个代码示例使用 State 而另一个使用 ActionReducer 和 State 作为 reducer 函数返回值的类型参数?为什么要选择这些函数签名中的一个而不是另一个?每个服务的目的是什么?

这本书是为 NgRx 2.2.1 编写的,而示例应用程序是为最新版本的 NgRx(版本 4.1.1)编写的。我猜想返回类型的差异不能简单地用 NgRx 版本的差异来解释,因为最新版本的 NgRx 也有 ActionReducer。

谢谢!

4

1 回答 1

6

ActionReducer 是StoreModule在导入期间传递给减速器的集合

  • Reducer 应始终返回初始状态的类型SomeInterface在您的情况下)

    export interface SomeInterface{
       ....
    }
    const initialState: SomeInterface= {
       ....
    };
    export function reducer(state = initialState, action: Actions): SomeInterface{...}
    
  • ActionReducer 应该是 reducer 的集合,它需要一个类型接口,该接口将是应用程序的应用商店接口,这个集合称为Reducer Factory

    export const reducers: ActionReducerMap<AppStore> = {
           someInterfacerSlice: someInterface.reducer,
    };
    
  • 为模块定义一个全局应用商店接口,如下所示,

    export interface AppStore {
          someInterfaceSlice: SomeInterface;
          stateSlice: StateSlice;
    }
    
于 2017-11-10T21:05:42.270 回答