Redux更新嵌套数据[不变的更新模式] [英] Redux updating nested data [Immutable Update Patterns]
问题描述
任何人都可以使用此更新模式进行帮助.我没有使用像immer这样的库.
Can anyone help with this update pattern. I am not using any libraries like immer.
我必须更新一个嵌套对象,数据看起来像dis
I have to update a nested object and the data looks like dis
样本数据
{
isFetching: false
data:{
nba : {
stack :{
1:[]
}
}
}
}
我的减速机
{
...state,
isFetching: false,
data: {
...state.data,
[action.payload.team]: {
...state[action.payload.team],
[action.payload.framework]: {
...state[action.payload.framework],
[action.payload.build]: action.payload.resp
}
}
}
};
我可以更新到第二级,但是无法更新第三个孩子. 谁能告诉我我想念的地方.
I am able to update until second level but unable to update third child. can anyone throw a light on where i am missing it.
我在codeandbox上做了一个演示. https://codesandbox.io/s/todos-0ygrs
I put a demo on codesandbox. https://codesandbox.io/s/todos-0ygrs
单击折叠和内部折叠项.我在下面的控制台中记录了状态更改.正如您在最后一级看到的那样,内部版本号已被替换为新版本号.
Click on collapse and inner collapse items. I am logging the changes for the state in the console below. As you can see at last level, build numbers are getting replaced with the new one's.
当前行为 展开nba和所有三个孩子
{
nba: {
stack:{
3:[]
}
}
预期的行为: 在扩展堆栈和所有三个孩子之后
{
nba: {
stack:{
1:[],
2:[],
3:[]
}
}
}
推荐答案
我以某种方式发现了自己的错误,希望以后能对某人有所帮助
Somehow i figured out my mistake, Hope it help someone in future
初始状态不能为null,应该为空对象,并且更新模式应采用这种方式
{
...state,
isFetching: false,
data: {
...state.data,
[action.payload.team]: {
...state.data[action.payload.team],
[action.payload.framework]: {
...state.data[action.payload.team][action.payload.framework],
[action.payload.build]: action.payload.resp
}
}
}
};
如果失败,请尝试这种方式
let teamTemp = { ...state.data[action.payload.team]}
{
...state,
isFetching: false,
data: {
...state.data,
[action.payload.team]: {
...teamTemp ,
[action.payload.framework]: {
...teamTemp[action.payload.framework],
[action.payload.build]: action.payload.resp
}
}
}
};
我已经分叉了我的codeandbox,并更新了最新代码.
I have forked my codesandbox and updated latest code.
新代码: https://codesandbox.io/s/todos-zqeki
这篇关于Redux更新嵌套数据[不变的更新模式]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!