State vs ActionReducer<State> 作为 NgRx reducer return 类型

State vs ActionReducer<State> as NgRx reducer return type

我正在审查 example application provided by NgRx 的代码。我注意到示例应用程序中的每个 reducer 函数都有一个 return 值,该值由该特定 reducer 的 State 接口输入。例如,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 and NgRx 时,偶然发现了一个显示 reducer 函数的通用主体结构的代码片段(第 24-25 页)。代码对于通用结构,reducer 函数的 return 值显示为 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> {

为什么一个代码示例使用 State 而另一个使用 ActionReducer 并将 State 作为 reducer 函数 return 值的类型参数?为什么要选择这些函数签名中的一个而不是另一个?每个都有什么用途?

这本书是为 NgRx 2.2.1 编写的,而示例应用程序是为最新版本的 NgRx(4.1.1 版)编写的。我猜无法简单地解释 return 类型的差异由于 NgRx 版本的不同,因为最新版本的 NgRx 也有 ActionReducer。

谢谢!

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

  • Reducer 应始终return 初始状态的类型SomeInterface 在你的情况下)

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

    export const reducers: ActionReducerMap<AppStore> = {
           someInterfacerSlice: someInterface.reducer,
    };
    
  • 如下定义模块的全局应用商店界面,

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