Dynamic key in immutability update helper for arra

2020-05-14 03:54发布

https://facebook.github.io/react/docs/update.html

I have an update function that receives an index along with the event so as to alter the value for that specific item in the array.

How do I get index to be evaluated instead of treated as a set key in this scenario? Is it even possible?

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

Right now this obviously doesn't work because it's attempting to update this.state.items['index']['amount'] which is not set, when I want to modify this.state.items[1]['amount'] for an index of 1.

1条回答
等我变得足够好
2楼-- · 2020-05-14 04:24

You could use ES6 computed property names, which would look like this with your index variable:

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

According to this ES6 compatability table, React's JSX transpiler supports them when its Harmony transforms are enabled, or you could use Babel instead (since react-tools is being deprecated in favour of Babel anyway).

Failing that, you could use a helper function to create an object with a given named property:

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})
}
查看更多
登录 后发表回答