2017-10-18 7 views
-1

Reduxの減速からのオブジェクトのサブ要素の配列にアクセスする方法:私はこのような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": [] 
      }] 
     }] 
     }] 
    }] 
}] 

も素敵な形式のデータである:

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を見て、'immutability-helper' libraryからfnの更新をチェックしてくださいImmutable.js

0

を使用することをお勧めし、その中で推奨さは、ドキュメントそのものを反応させます。

関連する問題