空状态调用NgRX效果

时间:2018-12-12 21:55:11

标签: angular ngrx ngrx-store ngrx-effects

我在使用redux应用程序时遇到了一些麻烦。假设有几个动作会更新状态。触发NgRX效果后,状态突然消失,降到减速器的下一个动作取为initialState。

这是我的作用:

@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,状态为空。我想念什么吗?

P.S。将分派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 };
    }
}

}

1 个答案:

答案 0 :(得分:1)

减速器应始终具有default的情况。

每个动作都通过应用程序中加载的每个reducer传递。这意味着,如果您不处理减速器内部的“其他”操作,则减速器将返回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;
}
相关问题