angular - 以空状态调用 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 };
}
}
}
解决方案
你的减速器应该总是有一个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;
}
推荐阅读
- r - 在R中的方法中将对象转换为字符串
- javascript - 使用 Tampermonkey 到达最后一页时停止函数
- graphql - 什么是 GraphQL 中的标量类型
- model - 如何在 UIMA Ruta 中为外部分析引擎设置模型
- postgresql - postgresql 根据存储在另一个表中的值更新表列
- python - 如何使用 Python 脚本将文件从 SFTP 位置下载到 Google 存储桶
- python - 如何将每一行解析为熊猫的第二列
- animation - SwiftUI 中事件触发的动画
- unity3d - 更改游戏对象的颜色显示为白色而不是请求的颜色
- c++ - 在 llvm IR 中获取函数的参数名称