ActionReducerMap 上的 Angular NgRx 类型问题
Posted
技术标签:
【中文标题】ActionReducerMap 上的 Angular NgRx 类型问题【英文标题】:Angular NgRx type problem on ActionReducerMap 【发布时间】:2022-01-07 15:35:24 【问题描述】:我正在编写一个小型 Angular 应用程序来学习 NgRx,但我在配置减速器时遇到了困难,我认为问题与 Angular 严格模式有关,但我没有找到任何相关信息。
我正在使用以下设置:
角 13 NgRx 13 节点 16common.actions.ts
import createAction from '@ngrx/store';
export const isLoading = createAction('[Common] isLoading');
common.reducer.ts
import Action, createReducer, on from '@ngrx/store';
import * as actions from './common.actions';
export interface CommonState
isLoading: boolean;
export const commonState: CommonState =
isLoading: false,
;
const _commonReducer = createReducer(
commonState,
on(actions.isLoading, commonState => (commonState))
);
export function commonReducer(state: CommonState, action: Action)
return _commonReducer(state, action);
app.reducer.ts(这是我的全局文件)
import commonReducer, CommonState from "~/common/common.reducer";
import ActionReducerMap from "@ngrx/store";
export interface GlobalState
common: CommonState
export const appReducers: ActionReducerMap<GlobalState> =
common: commonReducer
但是编译器抛出以下错误
TS2322: Type '(state: CommonState, action: Action) => CommonState' is not assignable to type 'ActionReducer<CommonState, Action>'. Types of parameters 'state' and 'state' are incompatible. Type 'CommonState | undefined' is not assignable to type 'CommonState'. Type 'undefined' is not assignable to type 'CommonState'. app.reducer.ts(5, 3): The expected type comes from property 'common' which is declared here on type 'ActionReducerMap<GlobalState, Action>'
【问题讨论】:
【参考方案1】:你可以试试这个
export function commonReducer(state: CommonState | undefined, action: Action)
return _commonReducer(state, action);
【讨论】:
这解决了问题,谢谢!,还阅读了我发现可以在模块中使用 forFeature 但我正要尝试的所有文档。 是的,正确。我也建议使用 forFeature ,因为它更简单一些。此外,如果您使用 Angular Ivy,则不再需要将 reducer 包装到函数中。在您的情况下,这意味着您可以简单地使用_commonReducer
而不是 commonReducer
我尝试了 forFeature,它很容易实现,我还安装了 ngrx 原理图,当我创建一个新的功能状态时,它会像你说的那样创建 reducer 函数,谢谢!以上是关于ActionReducerMap 上的 Angular NgRx 类型问题的主要内容,如果未能解决你的问题,请参考以下文章
如何在 getReducers():ActionReducerMap<fromFeature.State> 中返回 reducer 映射?