簡體   English   中英

未處理的運行時錯誤類型錯誤:無法讀取未定義的屬性“計時器”

[英]Unhandled Runtime Error TypeError: Cannot read property 'timer' of undefined

我正在使用 React 創建秒表。 我點擊了開始按鈕,秒表開始了,但是當我點擊停止按鈕時,我收到了TyperError

 import React from 'react'; class Home extends React.Component { constructor(props) { super(props); this.state = {secondsElapsed: 0}; this.handleStartClick = this.handleStartClick.bind(this); } getSeconds() { return ('0' + this.state.secondsElapsed % 60).slice(-2); } getMinutes() { return Math.floor(this.state.secondsElapsed / 60); } getHours() { return Math.floor((this.state.secondsElapsed / 60) / 60); } handleStartClick() { this.timer = setInterval(() => { this.setState({ secondsElapsed: (this.state.secondsElapsed + 1) }); }, 1000) } handleStopClick() { clearInterval(this.timer); } render() { return ( <div> <h1>{this.getHours()}:{this.getMinutes()}:{this.getSeconds()}</h1> <button type="button" onClick={this.handleStartClick}> start </button> <button type="button" onClick={this.handleStopClick}> stop </button> </div> ); } } export default Home;

即使出現錯誤,秒表也會繼續運行。 我想知道它是否無法讀取this.timer ,因為它是在 function、 handleStartClick中創建的。

您忘記將其綁定this handleStopClick 如果不這樣做, this不是組件的this

constructor(props) {
    super(props);
    this.state = {secondsElapsed: 0};
    this.handleStartClick = this.handleStartClick.bind(this);
    this.handleStopClick = this.handleStopClick.bind(this);
}

使用箭頭函數很容易避免這種情況,它們為您綁定父級的this

handleStartClick = () => {
    this.timer = setInterval(() => {
        this.setState({
            secondsElapsed: (this.state.secondsElapsed + 1)
        });
    }, 1000)
}

handleStopClick = () => {
    clearInterval(this.timer);
}

您已經在構造函數中正確綁定handleStartClick

this.handleStartClick = this.handleStartClick.bind(this);

你需要對handleStopClick做同樣的事情:

this.handleStopClick = this.handleStopClick.bind(this);

兩種情況下的原因是相同的——確保在 function 中對this的任何引用仍然是指組件實例。 否則,當作為事件處理程序調用時,“上下文丟失”, this變得undefined - 正如您所看到的。

暫無
暫無

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

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