Why does ReactJs say that the "warning counter:" is defined but never used ", but the variable is used?

This is part of the 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, the browser will read these warning lines in the 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 use the counter here: "console.log (this.state.counter);". Why is this error message?

Why if i change

  this.setState((prevState, props) => { counter: props.counter + 1 }); 

with

  this.setState({ counter: props.counter + 1 }); 

works?

+5
source share
1 answer

Because

 counter: props.counter + 1 

means creating a label called counter . However, you never use this label after.

You probably wanted

 this.setState((prevState, props) => ({ counter: props.counter + 1 })); 

Note that you just need to wrap {} in the arrow function with parentheses. Otherwise, {} considered as a block of the function body, not the object returned from this function of the function that you want in your case.

+3
source

Source: https://habr.com/ru/post/1260529/


All Articles