我有一个ngrx商店,初始状态类似于。
const state = {
child1: {...},
child2: {...},
}
和一个ActionReducerMap,如下所示。
const reducerMap = {
child1: reducer1,
child2: reducer2,
}
现在我想在child1和child2的同一级别添加一个 "加载 "状态,以跟踪两个子代的加载情况(它们是相互关联的)。为了实现这个目标,我更新了初始状态,如下所示。
const state = {
child1: {...},
child2: {...},
loading: false,
}
我试着用metareducer,它位于reducer1和reducer2的顶部,就像这样。
export function metaReducer(reducer) {
return function reduce(state, action) {
switch(action.type) {
case CommonActionTypes.UpdateLoading: {
return {
...,
loading: action.loading
}
}
default:
return reducer(state, action);
}
}
}
我将其添加到特征存储中,如下所示:
StoreModule.forFeature('myStore', compose(metaReducer, combineReducers)(reducerMap))
在应用程序中,我在一些更新child1和child2的效果中调用了UpdateLoading动作。然而,这并没有像我预期的那样工作。
{
child1: {...},
child2: {...},
}
使用meta-reducer更新共同状态的方法是否正确?如何才能让这个方法成功?
尝试在这两种情况下使用reducer函数。
export function metaReducer(reducer) {
return function reduce(state, action) {
switch(action.type) {
case CommonActionTypes.UpdateLoading: {
return reducer({ // <- wrap it.
...state,
loading: action.loading
}, action);
}
default:
return reducer(state, action);
}
}
}
而在 .forRoot
这样的。
StoreModule.forRoot({/*...*/}, {
metaReducers: [metaReducer],
}),