ReactJS setState具有多个嵌套数组

时间:2015-09-09 19:47:57

标签: reactjs immutability

考虑以下结构:

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}}
);

...但这不是正确的语法。那么如何保持我的状态不可变,但仍然更新数组项的这个嵌套属性?

1 个答案:

答案 0 :(得分:9)

你会像这样使用它

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

请参阅nested collections