繁体   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