[英]React Redux Immutable Deeply Nested Array
I have this structure 我有这个结构
Server response from the API 来自API的服务器响应
server response json 服务器响应json
Each of this topics must be in a separate response 每个主题都必须在单独的响应中
So basically the array has 3 levels 所以基本上数组有3个层次
I want to add a new subticket in a specific ticket in a specific 我想在特定票证中的特定子票中添加新子票证
This is the state graph 这是状态图
this works but obviously mutable 这可行,但显然易变
state[topic_id].tickets[ticket_index].subtickets = state[topic_id].tickets[ticket_index].subtickets.concat(action.subticket);
return {...state};
this also works and is immutable but it appends to the second layer ( tickets ) 这也可以工作并且是不可变的,但是会附加到第二层(ticket)
return {
...state
,[topic_id]:{
...state[topic_id]
,tickets:[
...state[topic_id].tickets
,action.subticket
]
}
} ;
considering this , this should work, but it does not 考虑到这一点,这应该工作,但不起作用
return {
...state
,[topic_id]:{
...state[topic_id]
,tickets:[
...state[topic_id].tickets
,[topic_id]:[
...state[topic_id].tickets[topic_id],
subtickets:[
...state[topic_id].tickets[topic_id].subtickets,
action.subticket
]
]
]
}
}
I am trying for 2 days I have no idea what is wrong with the last statement 我尝试了2天,我不知道最后一句话有什么问题
update: this works 更新:这有效
import { cloneDeep } from 'lodash';
{...}
let newState = cloneDeep(state);
newState[topic_id].tickets[ticket_index].subtickets = newState[topic_id].tickets[ticket_index].subtickets.concat(action.subticket);
return newState;
from what I understand, cloneDeep is not very performant 据我了解,cloneDeep的表现不是很好
still, a answer for what is wrong with the 3rd piece of code from the original comment would be appreciated 不过,对于原始注释中的第三段代码有什么问题的答案,我们将不胜感激。
try below: 请尝试以下方法:
{
...state,
[topic_id]: {
...state[topic_id],
tickets: [
...state[topic_id].tickets.slice(0, ticket_index),
state[topic_id].tickets[ticket_index] = {
...state[topic_id].tickets[ticket_index],
subticket: [
...state[topic_id].tickets[ticket_index].subticket,
{id: "st15"} // new subticket
]
},
...state[topic_id].tickets.slice(ticket_index + 1)
]
}
}
Hope it helps. 希望能帮助到你。 Thanks
谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.