angular - Ngrx 存储:更新 ActionReducerMap 之外的公共状态
问题描述
我有一个初始状态类似于的 ngrx 商店:
const state = {
child1: {...},
child2: {...},
}
使用 ActionReducerMap 如下:
const reducerMap = {
child1: reducer1,
child2: reducer2,
}
现在我想在与 child1 和 child2 相同的级别添加一个“加载”状态,以跟踪两个孩子(它们是相互连接的)的加载。为此,我将初始状态更新如下:
const state = {
child1: {...},
child2: {...},
loading: false,
}
我尝试使用位于 reducer1 和 reducer2 顶部的 metareducer,如下所示:
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 操作。但是,这并没有像我预期的那样工作。
- 首先,初始状态根本不尊重“加载”变量——它仍然认为原始状态是
{
child1: {...},
child2: {...},
}
- 状态中的“正在加载”变量仅在调用 UpdateLoading 操作时更新。通过所有后续操作,它将从状态中删除。这很奇怪,因为唯一作用于它的减速器是元减速器,而减速器 1 和减速器 2 分别作用于子状态 child1 和 child2。
使用 meta-reducer 更新公共状态是否正确?我怎样才能使这项工作?
解决方案
在这两种情况下都尝试使用 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],
}),
推荐阅读
- vim - 为什么它会在简单函数中引发错误“E523:此处不允许”?
- c++ - 将 cin 转换为 argc argv 输入。使用命令行传递值的新手
- javascript - 调整窗口大小时调整画布大小 (JavaScript)
- javascript - 将文件从本地 Angular 文件夹上传到服务器
- google-cloud-platform - 无法启动或移动 VM 实例
- uml - 如何用 UML 表示计数器类型的实体?
- java - Java 和 Jconn4 对 Sybase 16.3 的支持
- ruby - 在块之前用模拟修补猴子
- flutter - 在 Flutter 中 canvas.drawColor 是什么意思?
- amazon-dynamodb - 如何使用两列的哈希键和一列作为范围键创建 DynamoDb