This is a piece of a React Component:
constructor(props) {
super(props);
this.state = {
counter: 0
};
}
handleClick (event) {
this.setState((prevState, props) => {
counter: props.counter + 1
});
console.log(this.state.counter);
}
Trying to execute this page, browser wite these lines of warning in console:
/Volumes/Development/react-hello-world/src/App.js
17:13 warning Using 'LabeledStatement' is not allowed no-restricted-syntax
17:13 warning Unexpected labeled statement no-labels
17:13 warning 'counter:' is defined but never used no-unused-labels
17:22 warning Expected an assignment or function call and instead saw an expression no-unused-expressions
✖ 4 problems (0 errors, 4 warnings)
I am using the counter here: "console.log(this.state.counter);". Why that error message?
Why if I change
this.setState((prevState, props) => {
counter: props.counter + 1
});
with
this.setState({
counter: props.counter + 1
});
it works?
Because
counter: props.counter + 1
means create label named counter
. However, you indeed never use this label after.
You probably wanted
this.setState((prevState, props) => ({
counter: props.counter + 1
}));
Note, that you just need to wrap {}
in arrow function with parenthesis. Otherwise {}
is considered as function body block and not an object returned from this function function, which you want in your case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With