2015-09-09 45 views
2

考慮以下結構:ReactJS的setState多個嵌套數組

this.state = { 
    States: [{ 
    Abbreviation: "MA", 
    Cities: [{ 
     ID: 1, 
     Name: "Boston", 
     PropertyToUpdate: null 
    }, 
    { 
     ID: 2, 
     Name: "Springfield", 
     PropertyToUpdate: null 
    }] 
    }] 
} 

鑑於城市ID和值,我需要更新PropertyToUpdate屬性的值。所以我有一個看起來像一個功能:

handleUpdateProperty(cityID, newValue){ 
    // Do some things 
    this.setState({...}); 
} 

我已經做immutable helpers一些閱讀,但我不知道如何處理嵌套的兩層。我認爲它應該看起來像這樣:

var newState = React.addons.update(
    this.state.States[indexOfState].Cities[indexOfCity], 
    {PropertyToUpdate: {$set: newValue}} 
); 

...但這不是正確的語法。那麼如何讓我的狀態保持不變,但仍然更新數組項的嵌套屬性?

回答

9

你會使用這樣的

var newState = React.addons.update(this.state, { 
    States: { 
    [indexOfState]: { 
     Cities: { 
     [indexOfCity]: { 
      PropertyToUpdate: { 
      $set: newValue 
      } 
     } 
     } 
    } 
    } 
}) 

nested collections