【问题标题】:Line 17:20: 'count' is not defined no-undef第 17:20 行:'count' 未定义 no-undef
【发布时间】:2021-10-23 19:24:34
【问题描述】:

我正在尝试使用按钮显示每次点击的计数,但我的代码遇到了问题。当我运行我的代码时,它无法编译,但是当您检查页面时,您可以看到正在显示的时间。这是我的代码。

import React from 'react'
export default class Profile extends React.Component{
    constructor(){
        super();
        this.state={
            name:'Abdur Rehman',
            email: 'abdur@gmail.com',
            count: 0,
        }
    }
    test(){
        this.setState({
            name: 'Jamal',
            email: 'jamal123@gmail.com',
            count: count+1
            }
        )
    }
    render(){
        return(
            <div>
                <h1>hello {this.state.name}</h1>
                <h1>Email: {this.state.email}</h1>
                <h1>Count: {this.state.count}</h1>
                <button onClick={()=>{this.test()}}>Update Name</button>
            </div>
        );
    }
}

【问题讨论】:

    标签: javascript compiler-errors compilation


    【解决方案1】:

    我不确定为什么它会编译失败,但我可以在你的测试方法中发现一个逻辑错误。

    count: count+1
    

    应该是:

    count: this.state.count+1
    

    或者更好:

    count: this.state.count++
    

    这是因为您需要记住使用“this”关键字引用类 Profile 的实例。这是必要的,因为任何赋值都需要引用存储计数变量的显式路径,即 this.state.count。

    看看这对你有什么帮助:)

    【讨论】:

      【解决方案2】:

      导入以前的状态,也不要在constructor函数之外改变this.state变量,在测试函数中使用this.setState,这也会重新渲染组件

      import React from 'react'
      export default class Profile extends React.Component{
          constructor(){
              super();
              this.state={
                  name:'Abdur Rehman',
                  email: 'abdur@gmail.com',
                  count: 0,
              }
          }
          test(){
              this.setState({
                  ...this.state,
                  name: 'Jamal',
                  email: 'jamal123@gmail.com',
                  count: this.state.count + 1
                  }
              )
          }
          render(){
              return(
                  <div>
                      <h1>hello {this.state.name}</h1>
                      <h1>Email: {this.state.email}</h1>
                      <h1>Count: {this.state.count}</h1>
                      <button onClick={()=>{this.test()}}>Update Name</button>
                  </div>
              );
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-16
        • 2018-06-09
        • 2018-10-02
        • 2021-05-26
        • 2021-06-17
        • 2022-01-26
        相关资源
        最近更新 更多