Ngrx存储:更新ActionReducerMap之外的通用状态。

问题描述 投票:0回答:1

我有一个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动作。然而,这并没有像我预期的那样工作。

  1. 首先,初始状态根本不尊重 "加载 "变量--它仍然认为原始状态是 "加载"。
{ 
    child1: {...},
    child2: {...},
}
  1. 状态中的 "加载 "变量,只有在调用UpdateLoading操作时才会更新。在所有后续的操作中,它都会从状态中移除。这很奇怪,因为唯一作用于它的reducer是元reducer,而reducer1和reducer2分别作用于子状态child1和child2。

使用meta-reducer更新共同状态的方法是否正确?如何才能让这个方法成功?

angular ngrx ngrx-store ngrx-effects
1个回答
0
投票

尝试在这两种情况下使用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],
}),
© www.soinside.com 2019 - 2024. All rights reserved.