2016-08-24 51 views
0

我必须设置每月15日的倒计时。我能够成功获得倒计时到15日所需的差异值。但之后,我真的不知道我在做什么。无法获得倒数计时器的工作

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

我得到的错误无法读取属性天空

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> 
} 
+0

什么行代码是指向该错误信息? – jered

+0

JCD我更新了我的代码。我摆脱了这个错误通过这样做。状态&& .....但现在一切,除了this.state.days返回0 – joejoeso

+1

以及听起来像一个不同的问题,需要一个新的职位来回答:)当你的问题是回答你应该接受正确的答案,而不是仅仅改变你原来的帖子。发一个新帖子。 – jered

回答

1

第一次你的组件呈现,this.state不存在的,这就是为什么this.state.days抛出错误。为了解决这个问题,你既可以创建一个初始状态,或者如果this.state只存在渲染值:

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

好吧我摆脱了那个错误。现在一切都返回0免除日期。分钟,小时,秒= 0.将更新我的文章 – joejoeso

+0

我只是要开始一个新的职位,并接受这作为这一个正确的答案。谢谢 – joejoeso