倒计时后重启计时器Reactjs

时间:2018-05-24 05:57:08

标签: reactjs countdown antd

我正在研究一个简单的计数器,弹出一个模态,然后在模态中的计时器达到零后再次关闭,我的问题是我不知道如何重新启动第一个计数器。

希望你理解我。

感谢。

SAMPLE CODE

  componentWillMount() {
    this.timer = setInterval(this.countDown, 1000);
    this.setState({ seconds: this.props.time });
  }
  componentDidMount() {
    let timeLeftVar = this.secondsToTime(this.state.seconds);
    this.setState({ time: timeLeftVar });
  }
  countDown() {
    // Remove one second, set state so a re-render happens.
    let seconds = this.state.seconds - 1;
    this.setState({
      time: this.secondsToTime(seconds),
      seconds: seconds
    });

    // Check if we're at zero.
    if (seconds === 0) {
      clearInterval(this.timer);
      this.setState({
        visible: true
      });
      this.interval = setInterval(() => {
        this.setState({ currentCount: this.state.currentCount - 1 });
        if (this.state.currentCount === 0) {
          clearInterval(this.interval);
          this.setState({ visible: false });
        }
      }, 1000);
    }
  }

1 个答案:

答案 0 :(得分:0)

取出componentWillMount的内容并将其放在不同的函数中:

  componentWillMount() {
    this.foo();
  }

  foo() {
    this.timer = setInterval(this.countDown, 1000);
    this.setState({ seconds: this.props.time });
  }

然后你必须在interval到0时调用this.foo():

  this.interval = setInterval(() => {
    this.setState({ currentCount: this.state.currentCount - 1 });
    if (this.state.currentCount === 0) {
      clearInterval(this.interval);
      this.setState({ visible: false });
      this.foo();
    }
  }, 1000);