为什么 ReactJs 说"warning 'counter:' is defined but never used"但使用变量?



这是一个反应组件:

 constructor(props) {
     super(props);
     this.state = {
         counter: 0
     };
 }
 handleClick (event) {
     this.setState((prevState, props) => {
         counter: props.counter + 1
     });
     console.log(this.state.counter);
 }

尝试执行此页面,浏览控制台中的这些警告行:

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

我在这里使用计数器:" console.log(this.state.counter);"。为什么此错误消息?

为什么如果我更改

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

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

它有效?

因为

counter: props.counter + 1

表示名为counter的创建标签。但是,您确实永远不会使用此标签。

您可能想要

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

请注意,您只需要用括号将{}包装在箭头功能中即可。否则,{}被视为功能主体块,而不是从此功能中返回的对象,您需要在情况下。

相关内容

最新更新