2017-08-25 185 views
1

我实现了一个香草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

+3

需要绑定'this'(反应组件的上下文)与'updateTimer'功能,把这个线在构造函数中:'this.updateTimer =这.updateTimer.bind(this)' –

+0

谢谢你解决了! – Alex

+0

您的任何函数都没有适当的绑定。你需要绑定你引用属于React类上下文的'this'变量的每个函数 –

回答

2

当你通过this.updateTimersetTimeout你松散的上下文,即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); 
} 
+0

我相信也可以创建像'updateTimer =()=> {}'这样的组件方法来完成作业 – Kejt

+0

@Kejt it会但不同于上面的解决方案,它需要一个transpiler – Pavlo

+0

的确如此:),但为了支持完全的箭头功能,还应该有一个转译器,对吗? – Kejt