问题
我想使用ngrx链接多个高阶缩减器,以便缩减器中类似的代码部分只有一个实现。
我的应用程序具有许多功能非常相似的页面。他们的减速器看起来也很相似。对于此示例,我们考虑一个包含三个页面的应用程序:第一页,第二页和第三页。这些页面中的每一个都包含一个计数器,但是可以使用它执行不同的操作。如此:
可以找到此类应用程序的示例here。这是非常幼稚的实现,每页都有单独的化简器-每个化简器中都有很多非常相似的功能。
仅含一个高阶还原剂的解决方案
我设法使用高阶归约器将部分通用逻辑移至分离的代码段。在这种情况下,它是递增功能:
interface Actions {
incrementAction: ActionCreator<string>;
}
export const withIncrementation = ({ incrementAction }: Actions) => (
initState,
...actions
) =>
createReducer(
initState,
on(incrementAction, state => ({
...state,
counter: state.counter + 1
})),
...actions
);
这种高阶减速器可以像这样使用:
const pageOneReducer = withIncrementation({
incrementAction: PageOneActions.IncrementRequested
})(
initialState,
on(PageOneActions.DecrementRequested, (state: State) => ({
...state,
counter: state.counter - 1
}))
);
export function reducer(state: State | undefined, action: Action) {
return pageOneReducer(state, action);
}
到目前为止,一切正常。像这样正常运行的应用程序是here
使多个高阶异径管工作的问题
当我尝试链接多个高阶减速器工作时,问题开始了。在示例应用中 第二页和第三页都可以重置计数器(并且也可以递增),所以我现在想使用2个高阶减速器。我准备了新的高阶减速机,它与上一个非常相似,应该可以完成工作:
export const withReseting = ({ resetAction }: Actions) => (
initState,
...actions
) =>
createReducer(
initState,
on(resetAction, state => ({
...state,
counter: initialState.counter
})),
...actions
);
单独运行时效果很好,但是我找不到一种使它工作的方式, withIncrementation 和 withReseting 减速器。可以找到here的示例应用程序,但是它无法正常工作(看来我的状态完全停止了)。
Naive approach with 3 separate reducers