如何倒计时器在reactnative中运行

时间:2018-04-03 09:41:17

标签: javascript react-native

我有以下功能,但在调用setTimeout后显示错误 当我评论

// setTimeout(this.clock, 1000);

它的工作我想要倒数计时器。

this.state.text = "45:59"
  

undefined不是一个对象(evluating this.state.text)

clock() { 
    let presentTime = this.state.text;      

    var timeArray = presentTime.split(/[:]+/);
    var m = timeArray[0];
    var s = this.checkSecond((timeArray[1] - 1));
    if(s==59){m=m-1} 
    this.setState({text:  m + ":" + s}) 
    setTimeout(this.clock, 1000);
}

checkSecond(sec) {
    if (sec < 10 && sec >= 0) {sec = "0" + sec}; // add zero in front of numbers < 10
    if (sec < 0) {sec = "59"};
    return sec;
}

1 个答案:

答案 0 :(得分:1)

你需要绑定到不松散的上下文:

setTimeout(this.clock.bind(this), 1000);

setTimeout(() => this.clock(), 1000);