代码之家  ›  专栏  ›  技术社区  ›  Aessandro

反应倒计时错误

  •  1
  • Aessandro  · 技术社区  · 9 年前

    我在react组件中实现了vanilla js倒计时,如下所示:

    import React, { Component } from 'react';
    
    class CustomCountDown extends Component {
        constructor(props) {
            super(props);
    
            this.endTime;
            this.msLeft;
            this.time;
            this.hours;
            this.mins;
            this.element;
        }
    
        twoDigits( n ){
            return (n <= 9 ? "0" + n : n);
        }
    
        updateTimer() {
            this.msLeft = this.endTime - (+new Date);
            if (this.msLeft < 1000 ) {
                element.innerHTML = "countdown's over!";
            } else {
                this.time = new Date(this.msLeft );
                this.hours = this.time.getUTCHours();
                this.mins = this.time.getUTCMinutes();
                this.element.innerHTML = (this.hours ? this.hours + ':' + this.twoDigits( this.mins ) : this.mins) + ':' + this.twoDigits( this.time.getUTCSeconds() );
                setTimeout( this.updateTimer, this.time.getUTCMilliseconds() + 500 );
            }
        }
    
        countdown( elementName, minutes, seconds ) {
            this.element = document.getElementById( elementName );
            this.endTime = (+new Date) + 1000 * (60*minutes + seconds) + 500;
            this.updateTimer();
        }
    
        componentDidMount() {
            this.countdown("count", 1, 30);
        }
    
        render() {
            return(
                <div id="count">
                </div>
            );
        }
    }
    
    export default CustomCountDown;
    

    我不明白为什么会出现以下错误:

    enter image description here

    1 回复  |  直到 9 年前
        1
  •  3
  •   Pavlo    9 年前

    当你经过时 this.updateTimer 到 setTimeout this

    setTimeout( this.updateTimer.bind(this), this.time.getUTCMilliseconds() + 500 );
    
    setTimeout( () => this.updateTimer(), this.time.getUTCMilliseconds() + 500 );
    

    updateTimer 在构造函数中。这不会每次都创建新函数 updateTimer

    constructor(props) {
        // ...
    
        this.updateTimer = this.updateTimer.bind(this);
    }