我尝试使用按钮显示每次点击的次数,但我的代码遇到了问题。当我运行我的代码时,它无法编译,但是当您检查页面时,您可以看到正在显示的时间。这是我的代码。
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>
);
}
}
最佳答案
我不确定为什么它会编译失败,但我可以在您的测试方法中发现逻辑错误。
count: count+1
应该是:
count: this.state.count+1
或者更好:
count: this.state.count++
这是因为您需要记住使用“this”关键字来引用类 Profile 的实例。这是必要的,因为任何赋值都需要引用存储计数变量的显式路径,即 this.state.count。
看看这对你有什么帮助:)
关于javascript - 第 17 行 :20: 'count' is not defined no-undef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69691335/