NgRx - 如何分割状态

NgRx - How states are sliced

我对每个 reducer 的各个状态如何分割有一些疑问。 在许多在线教程中(如 this one),有一个手动定义的根全局状态,它结合了所有称为 AppState.

的单独状态

当我们将包含所有 reducer 的对象字面量传递给 StoreModule 时,这样说是否正确:

StoreModule.provideStore({r1: ReducerFunc1, r2: ReducerFunc2, ...})

对象键 r1r2 可用于在使用字符串选择器时查询状态切片:

store.select("r1")

但是,如果我们想要类型安全,我们定义 AppState 接口,并确保对象键与传递给 NgRx 的 reducer 对象字面量的对象键相匹配,这样我们就可以使用 store.select(appstate => appstate.r1) (这是 AppState 接口唯一有用的案例吗?

我认为您必须设置 AppState 界面。例如,当您依赖注入商店时,您不能这样做:

constructor(private store: Store)

Store 必须采用如下界面:

constructor(private store: Store<AppState>)

鉴于您必须指定 AppState,您可能希望始终使用粗箭头函数来获取 AppState 切片,因为您可以获得类型安全。

store.select(appstate => appstate.r1)

要以这种方式设置类型安全:

export interface AppState {
     auth: AuthState;
     contacts: ContactsState;
     events: EventsState;
}

每个切片都有自己的界面。

然后设置减速器

export const reducers: ActionReducerMap<AppState> = {
    auth: fromAuth.reducer;
    contacts: fromContacts.reducer;
    events: fromEvents.reducer;
}

然后在你的应用模块中

imports: [
    StoreModule.forRoot(reducers),
],

例如,您的 auth reducer 将这样定义

export function reducer(state: AuthState = initialAuthState,
                        action: Action) {

等每个 reducer 都由它的键、auth reducer 和 auth 状态调用。