我需要使用React的不变性帮手更新数组中元素的一个属性。
我有这样的事情:
this.setState(React.addons.update(this.state.collection[index], {
property: { $set: !this.state.collection[index].property }
}));
其中index
实际上是集合中元素的索引,而property
是我试图切换的布尔值。
问题是,代码不是修改元素的property
,而是修改this.state
对象中的一个property
属性--所以它应该类似于{collection: [...], property: true}
。
在嵌套集合上,它说我应该使用一个以元素的索引作为键的散列,但是我把它放在一个变量中,因此它变得有点模糊:
this.setState(React.addons.update(this.state, {
collection: {
index: {
property: { $set: !this.state.collection[index].property }
}
}
}));
它实际上给了我一个Cannot read property 'property' of undefined
错误--也就是说,this.state.collection
没有一个index
属性,这是真的。
我怎样才能做到这一点?
我已经知道我应该使用$apply
而不是$update
--但这并不是重点:)
发布于 2015-12-10 12:53:13
可以使用动态属性使用变量index
的值作为属性名:
this.setState(React.addons.update(this.state, {
collection: {
[index]: { // <--
property: { $set: !this.state.collection[index].property }
}
}
}));
这在ES2015中是新的。
https://stackoverflow.com/questions/34211468
复制