繁体   English   中英

无法使倒数计时器工作

[英]can't get countdown timer to work

我必须将倒计时设置为每月15号。 我能够成功获得倒数到15号所需的差值。 但是之后,老实说,我不知道自己在做什么。

计算完差异后,我计算了天,小时,分钟,秒。

我收到错误无法读取属性Days Null

export default React.createClass({
tick: function(){

var currentDate = new Date();
var date_till_15 = new Date()

if(currentDate.getDate() < 15){
    var days_till_15 = 15 - currentDate.getDate();
    date_till_15 = new Date(date_till_15.setDate(currentDate.getDate() + days_till_15 ));
}else if(currentDate.getDate() > 15){
    date_till_15 = new Date(date_till_15.setMonth(currentDate.getMonth() + 1));
    date_till_15 = new Date(date_till_15.setDate(15));
}
    var difference =  date_till_15 - currentDate;
    var daysLeft = 0, hoursLeft = 0, minutesLeft = 0, secondsLeft = 0;
    if(difference > 0){
        daysLeft = Math.floor( difference / (1000*60*60*24) );
        difference -= daysLeft * (1000*60*60*24);
        hoursLeft = Math.floor( difference / (1000*60*60) );
        difference -= hoursLeft * (1000*60*60);
        minutesLeft = Math.floor( difference / (1000*60) );
        difference -= minutesLeft * (1000*60);
        secondsLeft = Math.floor( difference/1000 );

      this.setState({
        days: daysLeft,
        hours: hoursLeft,
        minutes: minutesLeft,
        seconds: secondsLeft
      });
  } else {
        clearInterval( this.timeInterval );
        this.setState({expired: true});
    }
},

componentDidMount: function(){
    this.timeInterval = setInterval( this.tick.bind(this), 1000);
},

render() { 
    return <div> <div> this.state.days</div>

           </div>
}

组件第一次呈现时, this.state不存在,这就是为什么this.state.days抛出该错误的原因。 为了解决这个问题,您可以创建一个初始状态,或者仅在this.state存在时才呈现该值:

render() { 
    return <div>{this.state && this.state.days}</div>
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM