I am getting error shown in image for the below code:
handlechange(event) {
this.setState (prevState => {
return(
checked : !prevState.checked
);});
}
But when I changes round brackets after "return" into curly, it runs fine. I mean what's happening under the hood? What causes the error to go away?
handlechange(event) {
this.setState (prevState => {
return{
checked : !prevState.checked
}});
}
This isn't a React thing. Your first example is just invalid JavaScript syntax.¹ Your second example is valid syntax, returning an object created via an object initializer (often called an object "literal," {checked: !prevState.checked}
).
¹ The ()
after return
wrap an expression, and then within the expression you have checked: !prevState.checked
which looks like a labelled statement. But you can't put a labelled statement where an expression is expected.
Side note: Another way to write that is to use property destructuring in the parameter list and a shorthand property in the object initializer:
handlechange(event) {
this.setState(({checked}) => {
checked = !checked;
return {checked};
});
}
In the case that is working correctly, you are returning a JavaScript object (defined by the curly braces). That appears to be what you want to do, given the property-colon-value notation you are using, but the curly braces are required to signify the object in JavaScript.
{
key: value
}
is a legal object definition, but
(
key: value
)
is not.
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.