redux - redux:在大状态树的叶节点中设置状态
问题描述
我有一个包含其他不可变对象的不可变对象,并且 redux 状态树设置为最顶层对象的实例:
records.js
:
const TypeC = newRecord({
content: null
})
const TypeB = newRecord({
typeC: new TypeC;
})
export const TypeA = newRecord({
typeB: new TypeB;
})
reducer.js
:
import {
TypeA,
} from './records';
import types from './types';
const applicationReducer = (state = new TypeA(), action) => {
switch (action.type) {
...
}
default:
return state;
}
};
我的问题是:如何编写 reducer 代码来更改content
TypeC 中的字段?我试过类似的东西
CASE types.UPDATECONTENT: {
return state.get('typeB').get('typeC').set('content', "new content")
}
但这似乎只返回TypeC
我的状态树的一部分,当我需要从根开始的整个树时。
解决方案
state.get('typeB').get('typeC').set('content', "new content")
沿着树向下并修改 typeC 的属性“内容”。但是由于 immutable 是immutable,它不会修改任何内容,它会返回一条具有更新值(!)的新记录。state
和'typeC'之间的东西没有被触及。此外,set
返回新创建的记录,因此您可以有效地state
使用更新的typeC
.
更新嵌套对象的一种简单方法是使用名为 的“深度持久更改” <operation>In
,例如setIn
. 它也负责创建更新的中间对象。
TL/DR:
CASE types.UPDATECONTENT: {
return state.setIn(['typeB', 'typeC','content'], "new content");
}
推荐阅读
- python - 任何人都知道如何从 tcp 协议更改为 http 协议
- android - Android : 在 JitsiMeetView 之后 CameraX 不打开
- java - 如何在 Angular 侧边栏中添加外部工具提示?
- python - TensorBoard 中的 hp_metric 是什么以及如何摆脱它?
- android - (android) 如何从 DialogFragment 实现多选?
- node.js - 如何将 socket.io 连接到非网站应用程序?
- python - 熊猫在行中获取最大 ID 并添加到空行
- flutter - 如何在从另一个小部件继承的小部件中设置数据?
- javascript - VueJS- 在 v-for 循环中渲染表单,该循环引用最初为空的对象数组
- php - 如何在 laravel 刀片的 foreach 循环中获得第 n 行?