简体   繁体   中英

How to dynamically set value of an object property in reactJS state?

Let's say a component has state such as:

this.state = {
  enabled: {
    one: false,
    two: false,
    three: false
  }
}

How can this.setState() be used to set the value of a dynamic property?

For instance, this does not work:

let dynamicProperty = "one"
this.setState({
  enabled[dynamicProperty]: true
})

However, this does work, but is also bad practice:

this.enabled = {
  one: false,
  two: false,
  three: false
}
let dynamicProperty = "one"
this.enabled[dynamicProperty] = true;

How can this.setState() be used to accomplish the same thing?

You need to create a copy of the original object and only change the property you want to update. The easiest way to do that is to use the object spread operator:

this.setState(currentState => ({enabled: {...currentState.enabled, one: true}}));

or in a more verbose form:

this.setState(currentState => {
    const enabled = {...currentState.enabled, one: true};
    return {enabled};
});

If the property name is only known at runtime you can do it like this:

const setEnabled = name => {
    this.setState(currentState => ({enabled: {...currentState.enabled, [name]: true}}));
};

The standard practice is to copy the the state, modify the copied state, then set state using that clone, like this:

//with spread operator
const enabledClone = {...this.state.enabled};
enabledClone.one = true;
this.setState({enabled : enabledClone});

You can use braces around an object's key to use a variable to determine the key

const dynamicKey = 'one';
const newObj = {[dynamicKey]: true} //equals {one: true}

Since this.setState only merges on toplevel keys, you will have to create a copy of the current enabled object and use the braces notation:

 let dynamicProperty = "one"
 this.setState({
   enabled: {...this.state.enabled, [dynamicProperty]: true}
 })   

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