admin管理员组

文章数量:1401621

Let's say a ponent 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 acplish the same thing?

Let's say a ponent 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 acplish the same thing?

Share Improve this question asked Sep 26, 2019 at 0:34 JimJim 2,3227 gold badges42 silver badges77 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

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}
 })   

本文标签: javascriptHow to dynamically set value of an object property in reactJS stateStack Overflow