我收到了像这样的API的回复:
[{
"id": 1,
"name": "Microsoft",
"status": true,
"consoles": [{
"id": 4,
"name": "Xbox",
"status": true,
"subconsoles": [{
"id": 7,
"name": "Xbox 360",
"status": true,
"subconsoles": []
},
{
"id": 90,
"name": "Xbox One",
"status": false,
"subconsoles": [{
"id": 21,
"name": "Xbox One S",
"status": true,
"subconsoles": []
},
{
"id": 12,
"name": "Xbox One X",
"status": false,
"subconsoles": [{
"id": 41,
"name": "Xbox One X model 1",
"status": false,
"subconsoles": []
}]
}]
}]
}]
}]
以下是格式良好的数据:
我想要实现的是修改子控件的状态。 因此,从布局部分我传递了我想要更改的ID,但我真的被困在如何访问Redux的reducers中的子元素(最终是子子元素):
case SUBCONSOLES_ENABLE:
return {
...state,
id: action.payload.subconsoleId,
.....
}
答案 0 :(得分:1)
您需要先创建状态中每个阵列的副本,然后才能更改它们,以保持状态不变。有这么多级别,这将很快变得复杂!
case SUBCONSOLES_ENABLE:
let newState = [...state]; //create copy of state array
..... //find the index of the object in the newState array which you would want to change
let newConsoles = [...newState[index].consoles]; //create a copy of consoles
..... //find the index of the object in the newConsoles array which you would want to change
let newSubConsoles = [...newConsoles[index2].subconsoles];//create a copy of subconsoles
let subConsole = newSubConsoles.find((a)=>a.id===action.payload.subconsoleId); //find the object in the newConsoles array which you would want to change
let newSubConsole = {...subConsole} //make a copy of your object
..... //make your changes to the copy
//replace the old object with the new object in newSubConsoles
//replace subConsoles array with newSubConsoles array in newConsoles
// replace consoles array with newConsoles array in new State.
//and finally!!
return newState;
根据您所在州的形状,我建议您查看normalizing your state并使用Immutable.js
答案 1 :(得分:0)
查看'immutability-helper' library中的更新fn,它是反应文档中推荐的。