简体   繁体   中英

React-Native setState - both name and value from the same variable

Is it possible to enter only one argument to SetState that contains both the name and the value. See the example below. Is there something wrong with the brackets?

This would be handy when changing a lot of states at the same time. That is, first prepare them in one long string and execute setState only once. Thank you!

this.setState({myState: "help"}) // this works of course
whatstate='myState'
this.setState({[whatstate]: "me"}) // this too
whatstate2='myState: "please"' 
this.setState(whatstate2) // but how to make this work?
// if you like to work only with strings
var whatstate = {};
whatstate['myState1'] = 'help';
whatstate['myState2'] = 'me';
whatstate['myState3'] = 'please';

// ^ this will produce an object equivalent to this
//whatstate = {
//  myState1: 'help',
//  myState2: 'me',
//  myState3: 'please'
//}

// which you can use it to 'setState'
this.setState(whatstate);

You can call this.setState({ whatstate2 }) to achieve the same effect. This is the property value shorthand from ES6.

Reference: https://ariya.io/2013/02/es6-and-object-literal-property-value-shorthand

In case you'd like to update multiple states in one go, you can also do that like this.

this.setState({
    myState1 : newState1,
    myState2 : newState2
});

If the variable names are the same as the state names as mentioned previously, you can do.

this.setState({ myState1, myState2 });

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