首页 > 解决方案 > 以空状态调用 NgRX 效果

问题描述

我在 redux 应用程序的状态方面遇到了一些问题。假设有几个动作更新了状态。当一个 NgRX 效果被触发时,状态突然消失,下一个进入减速器的动作采用初始状态。

这是我的效果:

@Effect() getConfiguration$ = this.actions$.pipe(
    ofType(PlasmaAction.PlasmaActionTypes.GET_CONFIGURATION),
    switchMap((action: PlasmaAction.PlasmaActions) => {
        return this.plasmaService.send(action.payload).pipe(
            map(result => {
            return new PlasmaAction.SetConfiguration(result);
            })
        );
    })
);

直到调度 GET_CONFIGURATION 操作,状态都很好,但是状态看起来是这样的: redux-dev-tools-screenshot并且状态是空的。我错过了什么吗?

PS SET_CONFIGURATION 被调度并使用新配置更新状态,所有其他属性都恢复为初始属性。

@EDIT:这是我的减速器。在我这边进行一些调试:

export function plasmaReducer(state: PlasmaState, action: PlasmaActions) {
if (!state) {
    console.log('%c STATE IS EMPTY', 'color:red;');
    state = initialState;
}
switch (action.type) {
    case PlasmaActionTypes.CONNECTION_OPENED: {

        return { ...state, connected: true };
    }
    case PlasmaActionTypes.CONNECTION_CLOSED: {
        return { ...state, connected: false };
    }
    case PlasmaActionTypes.SET_CONFIGURATION: {
        return { ...state, configuration: action.payload };
    }
}

}

标签: angularngrxngrx-storengrx-effects

解决方案


你的减速器应该总是有一个default案例。

每个操作都通过应用程序中加载的每个减速器传递。这意味着如果您不处理减速器内部的“其他”操作,减速器将返回undefined,因此您会看到空状态。

要处理“其他”操作,请使用default案例并简单地按原样返回状态:

switch (action.type) {
    case PlasmaActionTypes.CONNECTION_OPENED: {

        return { ...state, connected: true };
    }
    case PlasmaActionTypes.CONNECTION_CLOSED: {
        return { ...state, connected: false };
    }
    case PlasmaActionTypes.SET_CONFIGURATION: {
        return { ...state, configuration: action.payload };
    }

    default:
         return state;
}

推荐阅读