反应计时器挂起:00(状态未更新)

时间:2016-04-03 22:59:03

标签: javascript reactjs timer state

我在React中有一个基本的计时器正常倒计时。唯一的问题是,当计时器的秒数达到'00'并且切换到'59'之前,它会持续一秒钟(或两秒钟)。我觉得我对状态仍然不满意,因为我花了一些时间进行调试,似乎无法弄清楚问题。

非常感谢任何帮助。谢谢。

代码:(问题似乎在定时器函数的if语句中)

const Clock = React.createClass({

  getInitialState: function() {
    return { currentCount: this.props.minutes, seconds: 10 };
  },

  startTimer: function() {
    var intervalId = setInterval(this.timer, 1000);
    this.setState({ intervalId: intervalId, minutes: this.state.currentCount - 1 });
  },

  pauseTimer: function() {
    clearInterval(this.state.intervalId);
    this.setState({ intervalId: this.props.minutes });
  },

  timer: function() {
    var minutes = this.state.minutes;
    var seconds = this.state.seconds;

    if (seconds === '00') {
      this.setState({ minutes: '0' + minutes - 1, seconds: 60 });
      this.setState({ currentCount: minutes + ':' + seconds });
      console.log('min: ' + minutes, 'sec: ' + seconds);
    } else {
      seconds--;
      seconds = seconds < 10 ? '0' + seconds : seconds;
      minutes = minutes < 10 ? '0' + minutes : minutes;

      this.setState({ currentCount: minutes + ':' + seconds, minutes: this.state.minutes, seconds: seconds });
    }
  },

  componentWillReceiveProps: function(nextProps) {
    this.setState({ currentCount: nextProps.minutes });
  },

  render: function() {
    return (
      <section>
        <button onClick={this.startTimer}>Start</button>
        <button onClick={this.pauseTimer}>Pause</button>
        <br></br>
        {this.state.currentCount}
      </section>
    );
  }

});

module.exports = Clock;

1 个答案:

答案 0 :(得分:1)

尝试在渲染功能中保持显示逻辑(左边填充零到分钟和秒),然后用59秒而不是60秒勾选分钟,例如:https://jsfiddle.net/reactjs/69z2wepo/

const Clock = React.createClass({

  getInitialState: function() {
    return { minutes: this.props.minutes, seconds: this.props.seconds };
  },

  startTimer: function() {
    var intervalId = setInterval(this.timer, 1000);
    this.setState({ intervalId: intervalId });
  },

  pauseTimer: function() {
    clearInterval(this.state.intervalId);
    this.setState({ intervalId: this.props.minutes });
  },

  timer: function() {
    var minutes = this.state.minutes;
    var seconds = this.state.seconds;

    if (seconds === 0) {
      this.setState({ minutes: minutes - 1, seconds: 59 });
    } else {
      seconds--;
      this.setState({ minutes: minutes, seconds: seconds });
    }
  },

  render: function() {
    var s = this.state.seconds,
        m = this.state.minutes;
    return (
      <section>
        <button onClick={this.startTimer}>Start</button>
        <button onClick={this.pauseTimer}>Pause</button>
        <br></br>
        {m < 10 ? '0' + m : m}:{s < 10 ? '0' + s : s}
      </section>
    );
  }

});