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

React timer hanging on :00 (state not updating)

本文关键字:状态 更新 计时器 挂起 React      更新时间:2023-12-10

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;

试着在渲染函数中保留显示逻辑(将零左填充到分钟和秒),并用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>
    );
  }
});