Dynamic key in immutability update helper for array

后端 未结 1 366
小鲜肉
小鲜肉 2021-01-30 17:27

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 i

相关标签:
1条回答
  • 2021-01-30 17:40

    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})
    }
    
    0 讨论(0)
提交回复
热议问题