考虑以下结构:
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}}
);
...但这不是正确的语法。那么如何保持我的状态不可变,但仍然更新数组项的这个嵌套属性?
答案 0 :(得分:9)
你会像这样使用它
var newState = React.addons.update(this.state, {
States: {
[indexOfState]: {
Cities: {
[indexOfCity]: {
PropertyToUpdate: {
$set: newValue
}
}
}
}
}
})