Reactjs 如何更新数组';反应中的元素是什么?

Reactjs 如何更新数组';反应中的元素是什么?,reactjs,Reactjs,我需要使用更新数组中元素的一个属性 我有这样的想法: this.setState(React.addons.update)(this.state.collection[index]{ 属性:{$set:!this.state.collection[index].property} })); 其中,index实际上是元素在集合上的索引,property是我试图切换的布尔值 问题是代码没有修改元素的属性,而是this.state对象中的属性属性-因此它变成了类似{collection:[…],pr

我需要使用更新数组中元素的一个属性

我有这样的想法:

this.setState(React.addons.update)(this.state.collection[index]{
属性:{$set:!this.state.collection[index].property}
}));
其中,
index
实际上是元素在集合上的索引,
property
是我试图切换的布尔值

问题是代码没有修改元素的
属性
,而是
this.state
对象中的
属性
属性-因此它变成了类似
{collection:[…],property:true}
的东西

上面说我应该使用一个散列和元素的索引作为键,但我把它放在一个变量中,所以它有点模棱两可:

this.setState(React.addons.update)(this.state{
收藏:{
索引:{
属性:{$set:!this.state.collection[index].property}
}
}
}));
它实际上给了我一个
无法读取未定义
错误的属性'property',即
this.state.collection
没有
索引
属性,这是真的

我如何才能做到这一点?


我已经知道我应该使用
$apply
而不是
$update
-但这不是重点:)

您可以使用动态属性将变量
索引的值用作属性名称:

this.setState(React.addons.update(this.state, {
  collection: {
    [index]: { // <--
      property: { $set: !this.state.collection[index].property }
    }
  }
}));
this.setState(React.addons.update)(this.state{
收藏:{
[索引]:{//