是否可以仅向SetState输入一个同时包含名称和值的参数。请参见下面的示例。括号有问题吗?

同时更改许多状态时,这将很方便。也就是说,首先将它们准备在一个长字符串中,然后仅执行一次setState。谢谢!

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

09-25 16:47