我正在重写redux状态,破坏子树,但是此后部分状态丢失了
const initialState = {
fetching: false,
data: {
events: null,
issues: null,
sla: {
daily: null,
weekly: null,
},
lastUpdate: null,
},
error: null,
};
case types.FETCH_DATA.SUCCESS:
return {
...state,
data: {
...state.data,
sla: {
...state.data.sla,
...payload.data.sla,
},
...payload.data,
},
fetching: false,
error: null,
};
{
events: ["event 1", "event 2"],
issues: ["issue 1", "issue 2"],
sla: {
daily: ["daily 1", "daily 2"],
}
{
fetching: false,
data: {
events: ["event 1", "event 2"],
issues: ["issue 1", "issue 2"],
sla: {
daily: ["daily 1", "daily 2"],
},
lastUpdate: null,
},
error: null,
}
data.sla.weekly丢失
{
events: ["event 1", "event 2"],
sla: {
daily: ["daily 1", "daily 2"],
}
{
fetching: false,
data: {
events: ["event 1", "event 2"],
issues: null,
sla: {
daily: ["daily 1", "daily 2"],
},
lastUpdate: null,
},
error: null,
}
在这种情况下... state.data解构工作正常,但是... state.data.sla无效
请有人帮助我!
答案 0 :(得分:1)
解构工作按预期进行,但顺序应更改
case types.FETCH_DATA.SUCCESS:
return {
...state,
data: {
...state.data,
sla: {
...state.data.sla,
...payload.data.sla,
},
...payload.data, <---- This is overriding the previous `sla` but the action contains `sla.daily` only, that's why your `sla.weekly` is gone
},
fetching: false,
error: null,
};
尝试更改顺序
case types.FETCH_DATA.SUCCESS:
return {
...state,
data: {
...state.data,
...payload.data, <-- Move up before `sla`
sla: {
...state.data.sla,
...payload.data.sla,
},
},
fetching: false,
error: null,
};
但是您的状态似乎相当复杂,如果可能的话,简化它可以使您的生活更轻松...