简体   繁体   中英

How to assign a value to an object property using variable?

I'm working on Reacr app. I have an object like this:

state = {
    property1: 'value',
    property2: 'value',
    property3: 'value',
    property4: 'value',
}

I want to assign a value to this object property through a function:

myFunc = (i) => {
     this.setState({
          this.state[i] = 'newValue'
     })  
}

But it can't be done because in this way I will directly mutate the state object. So I have a question how to get object property name and then assign a value to it? It would be nice if it can be possible in JavaScript to:

this.state[i] : 'ft-post ft-post-show'

Thank you for any ideas!

You set the value using an object assignment with with dynamic key syntax like

myFunc = (i) => {
     this.setState({
          [i]:  'ft-post ft-post-show'
     })  
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM