use*_*766 1 ngrx angular ngrx-store ngrx-store-4.0
我正在查看NgRx 提供的示例应用程序的代码。我注意到示例应用程序中的每个 reducer 函数都有一个返回值,该返回值由该State特定 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 {
Run Code Online (Sandbox Code Playgroud)
后来,我读了一本关于 NgRx 的书,名为Oren Farhi 的《使用 Angular 和 NgRx进行响应式编程》,并偶然发现了一段代码片段,显示了一个 reducer 函数的公共主体结构(第 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> {
Run Code Online (Sandbox Code Playgroud)
为什么一个代码示例使用State,另一个使用ActionReducer,将State作为reducer函数返回值的类型参数?为什么要选择这些函数签名中的一个而不是另一个?每个人的目的是什么?
这本书是为 NgRx 2.2.1 编写的,而示例应用程序是为最新版本的 NgRx(版本 4.1.1)编写的。我猜测返回类型的差异不能简单地用 NgRx 版本的差异来解释,因为最新版本的 NgRx 也有 ActionReducer。
谢谢!
ActionReducer 是一个减速器的集合,它被传递到StoreModule导入过程中
Reducer 应始终返回初始状态的类型(SomeInterface在您的情况下)
export interface SomeInterface{
....
}
const initialState: SomeInterface= {
....
};
export function reducer(state = initialState, action: Actions): SomeInterface{...}
Run Code Online (Sandbox Code Playgroud)ActionReducer 应该是一个 reducer 的集合,它需要一个类型接口,它将成为应用程序的应用商店接口,这个集合被称为Reducer 工厂
export const reducers: ActionReducerMap<AppStore> = {
someInterfacerSlice: someInterface.reducer,
};
Run Code Online (Sandbox Code Playgroud)为模块定义一个全局应用商店接口,如下所示,
export interface AppStore {
someInterfaceSlice: SomeInterface;
stateSlice: StateSlice;
}
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
1453 次 |
| 最近记录: |