2017-10-18 135 views
-1

我有一个API类似这样的响应访问的对象子元素的数组:如何从Redux的减速

[{ 
    "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": [] 
      }] 
     }] 
     }] 
    }] 
}] 

这里也是不错的格式的数据:

Online JSON Viewer

什么我正在努力实现的是修改次底盘的状态。 因此,从布局部分我通过什么我想改变ID,但我真的卡在如何访问终极版的减速机的子元素(最终子子元素):

case SUBCONSOLES_ENABLE: 
return { 
    ...state, 
    id: action.payload.subconsoleId, 
    ..... 
} 
+0

你能显示一些实际数据吗?这似乎是畸形的 –

+0

我用一种很好的方式添加了带有JSON视图的图像。 – Mark

回答

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