简体   繁体   English

React-Native setState - 来自同一变量的名称和值

[英]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. 是否可以只向SetState输入一个包含名称和值的参数。 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. 也就是说,首先在一个长字符串中准备它们并仅执行一次setState。 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.setState({ whatstate2 })来实现相同的效果。 This is the property value shorthand from ES6. 这是ES6的属性值简写。

Reference: https://ariya.io/2013/02/es6-and-object-literal-property-value-shorthand 参考: 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 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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