我正在尝试使用上下文API,而不是redux,因此在尝试将reducer组合在一起时遇到了这个问题。这是代码:
const mainReducer = (state: InitialStateType, action: AppMenuActions | AuthActions | LayoutActions) => ({
appMenu: AppMenuReducer(state.appMenu, action),
auth: AuthReducer(state.auth, action),
layout: LayoutReducer(state.layout, action),
});
如果没有类型,但我使用的是打字稿,它可以正常工作,因此我的每个化简器都根据该化简器采用AppMenuActions或AuthActions或LayoutActions采取的操作类型。因为我不知道在使用哪个动作时我会传递,所以我必须使用联合|用于mainReducer的动作arg。当我将该动作传递给每个reducer打字稿时会抱怨,因为例如AppMenuReducer动作仅采用AppMenuActions类型,但会传递给AppMenuActions | AuthAction | LayoutActions。我被卡住了,不知道该如何解决。谢谢您的帮助!
答案 0 :(得分:0)
因此,在阅读打字稿文档后,可以通过类型断言来完成,在这种情况下,我将使用:
const mainReducer = (state: InitialStateType, action: AppMenuActions | AuthActions | LayoutActions) => ({
appMenu: AppMenuReducer(state.appMenu, action as AppMenuActions),
auth: AuthReducer(state.auth, action as AuthActions),
layout: LayoutReducer(state.layout, action as LayoutActions),
});