以空状态调用的 NgRX 效果

NgRX effect called with empty state

我在 redux 应用程序的状态方面遇到了一些麻烦。假设有几个动作更新了状态。当 NgRX 效果被触发时,状态突然消失,下一个进入 reducer 的动作采用 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 };
    }
}

}

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

每个动作都通过应用程序中加载的每个减速器传递。这意味着如果你不处理减速器内部的 "other" 动作,减速器 returns undefined,因此你看到的是空状态。

要处理 "other" 操作,请使用 default 案例并简单地 return 状态:

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;
}