clearInterval 在 React Timer App 中不起作用

clearInterval not working in React Timer App

我一直在努力通过创建番茄钟应用程序来提高我的 React 技能。出于某种原因,我似乎无法 clearInterval 工作:

startTimer() {
    const { started } = this.state;
    var timer;
    if (!started) {
      timer = setInterval(this.countdown, 1000);
      this.setState({ started: true });
    }
    else {
      clearInterval(timer);
      this.setState({ started: false });
    }
  }

没有控制台错误。可以确认它肯定是 运行 条件语句的那一部分(当我登录 this.state.started 时它显示 false)。计时器只是不停地滴答作响,实际上并没有停止。

其余代码:

import React, { Component } from 'react';

class Timer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      secs: 60,
      started: false
    };
    this.startTimer = this.startTimer.bind(this);
    this.countdown = this.countdown.bind(this);
  }

  countdown() {
    this.setState({ secs: this.state.secs - 1});
  }

  startTimer() {
    const { started } = this.state;
    var timer;
    if (!started) {
      timer = setInterval(this.countdown, 1000);
      this.setState({ started: true });
    }
    else {
      clearInterval(timer);
      this.setState({ started: false });
    }
  }

  render() {
    const { secs } = this.state;
    console.log('secs:', secs)
    console.log('started:', this.state.started);
    return (
      <div className='timer' onClick={this.startTimer}>
        <h2>Session</h2>
        <h1>{this.props.session}:{secs == 60 ? '00': secs}</h1>
      </div>
    );
  }
}

export default Timer;

在构造函数中初始化this.timer。然后创建 setInterval 并将其分配给 this.timer,这将允许您稍后清除它。

import React, { Component } from 'react';

class Timer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      secs: 60,
      started: false
    };
    this.timer = null;
    this.startTimer = this.startTimer.bind(this);
    this.countdown = this.countdown.bind(this);
  }

  countdown() {
    this.setState({ secs: this.state.secs - 1});
  }

  startTimer() {
    const { started } = this.state;
    if (!started) {
      this.timer = setInterval(this.countdown, 1000);
      this.setState({ started: true });
    }
    else {
      clearInterval(this.timer);
      this.setState({ started: false });
    }
  }

  render() {
    const { secs } = this.state;
    console.log('secs:', secs)
    console.log('started:', this.state.started);
    return (
      <div className='timer' onClick={this.startTimer}>
        <h2>Session</h2>
        <h1>{this.props.session}:{secs == 60 ? '00': secs}</h1>
      </div>
    );
  }
}

export default Timer;

如果您不想创建 class

 if(condition_is_true){
   const checkUntilConditionIsFalse = setInterval(() => {
    if (condition_is_false) {
      clearInterval(checkUntilConditionIsFalse);
    }
  }, 1000);
}