我正在查看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 函数的返回值显示为由ActionReducer
withState
作为类型参数输入(在这种情况下调用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。
谢谢!