Javascript 数组的不可变更新帮助程序中的动态键

Javascript 数组的不可变更新帮助程序中的动态键,javascript,reactjs,ecmascript-6,Javascript,Reactjs,Ecmascript 6,我有一个更新函数,它接收一个索引和事件,以便更改数组中该特定项的值 在这种情况下,如何获得要评估的索引,而不是将其视为设置键?有可能吗 updateValue: function(index, e) { var items = React.addons.update(this.state.items, { index: { amount: {$set: e.target.value} } }); this.setState({ items: items

我有一个更新函数,它接收一个索引和事件,以便更改数组中该特定项的值

在这种情况下,如何获得要评估的
索引
,而不是将其视为设置键?有可能吗

updateValue: function(index, e) {
  var items = React.addons.update(this.state.items, {
   index: {
     amount: {$set: e.target.value}
   }
  });
  this.setState({
    items: items
  })
}
现在这显然不起作用,因为它正在尝试更新
this.state.items['index']['amount']
,当我想要修改
this.state.items[1]['amount']
的索引为1时,它没有设置。

您可以使用,它与
索引
变量类似:

updateValue(index, e) {
  var items = React.addons.update(this.state.items, {
    [index]: {
      amount: {$set: e.target.value}
    }
  })
  this.setState({items})
}
根据这一点,React的JSX transpiler在启用和谐转换时支持它们,或者您可以使用它们(因为无论如何)

否则,可以使用助手函数创建具有给定命名属性的对象:

function makeProp(prop, value) {
  var obj = {}
  obj[prop] = value
  return obj
}

// ...

updateValue: function(index, e) {
  var items = React.addons.update(this.state.items, makeProp(
    index, {
      amount: {$set: e.target.value}
    }
  ))
  this.setState({items: items})
}

谢谢你详尽的回答。我正在使用gem,尽管启用了文档中的harmony标志并确保了,但我还是得到了这个错误
uncaughtsyntaxerror:uncontractedtoken[
,因此我将坚持使用helper方法,直到他们将其与Babel一起提供。我被helper函数示例弄糊涂了。
this.state.items
是一个数组,您正在将其更新为
{1:{amount:$set:e.target.value}
。我仍在学习更新插件是如何工作的,但在我看来它不应该工作。假设它确实能工作,他难道不能刚刚完成
更新(this.state.items[index],{amount:{$set:e.target.value}}})
?更新对允许它工作的数组有特殊情况吗?