我正在嘗試使用按鈕顯示每次點擊的計數,但我的代碼遇到了問題。當我運行我的代碼時,它無法編譯,但是當您檢查頁面時,您可以看到顯示的時間。這是我的代碼。
import React from 'react'
export default class Profile extends React.Component{
constructor(){
super();
this.state={
name:'Abdur Rehman',
email: '[email protected]',
count: 0,
}
}
test(){
this.setState({
name: 'Jamal',
email: '[email protected]',
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>
);
}
}
uj5u.com熱心網友回復:
我不確定為什么它會無法編譯,但我可以在您的測驗方法中發現邏輯錯誤。
count: count 1
應該:
count: this.state.count 1
或者更好:
count: this.state.count
這是因為您需要記住使用“this”關鍵字來參考類 Profile 的實體。這是必要的,因為任何賦值都需要參考存盤計數變數的顯式路徑,即 this.state.count。
看看這對你有什么幫助:)
uj5u.com熱心網友回復:
匯入之前的狀態,也不要改變函式this.state外的變數constructor,this.setState在測驗函式中使用,這也會重新渲染組件
import React from 'react'
export default class Profile extends React.Component{
constructor(){
super();
this.state={
name:'Abdur Rehman',
email: '[email protected]',
count: 0,
}
}
test(){
this.setState({
...this.state,
name: 'Jamal',
email: '[email protected]',
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>
);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/334099.html
標籤:javascript 编译器错误 汇编
