簡體   English   中英

第 17:20 行:'count' 未定義 no-undef

[英]Line 17:20: 'count' is not defined no-undef

我正在嘗試使用按鈕顯示每次點擊的計數,但我的代碼遇到了問題。 當我運行我的代碼時,它無法編譯,但是當您檢查頁面時,您可以看到顯示的時間。 這是我的代碼。

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。

看看這對你有什么幫助:)

導入之前的狀態,也不要在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>
        );
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM