React 中的清除间隔 class

Clear interval in React class

所以,我们有了这个简单的 React 组件,它从父组件接收一个整数。单击按钮时,我们在屏幕上显示整数并开始倒计时。

问题是如何停止倒计时。在阅读其他 SO 帖子时,我发现了 clearInterval(),但似乎我在这里遗漏了一些东西。

如有任何帮助,我们将不胜感激。如果有人好心向我解释为什么示例代码没有按预期工作,将获得奖励积分。

    import React from "react";

    export default class TestInterval extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                countDown: this.props.countDown, // An integer from father component
            }
        }

        timer = () => {
            setInterval(() => {
                if (this.state.countDown === 0) {
                    this.stopCountDown();
                }
                this.setState( prevState => ({
                    countDown: prevState.countDown - 1, 
                }));
            }, 1000)
        }

        startCountDown = () => {
            this.timer();
        }

        stopCountDown = () => {
            clearInterval(this.timer); // Not working
        }

        render () {
            return (
                <div>
                    <button onClick={this.startCountDown}>
                        Start Countdown
                    </button>
                    <p>{this.state.countDown}</p>
                </div>
            );
        }
    }

您需要存储从 setInterval 返回的区间引用。
来自 docs:

It returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval().

因此您的代码应该如下所示:

this.interval = setInterval(() => {...

然后清除它:

 clearInterval(this.interval);

我会在状态真正设置后检查条件(setState 是异步的)你可以在 setState 的回调中进行。

this.interval = setInterval(() => {
      this.setState(prevState => ({
        countDown: prevState.countDown - 1,
      }), () => {
        if (this.state.countDown === 0) {
          this.stopCountDown();
        }
      });
    }, 1000)

运行 示例:

class TestInterval extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      countDown: this.props.countDown, // An integer from father component
    }
  }

  timer = () => {
    this.interval = setInterval(() => {
      this.setState(prevState => ({
        countDown: prevState.countDown - 1,
      }), () => {
        if (this.state.countDown === 0) {
          this.stopCountDown();
        }
      });
    }, 1000)
  }

  startCountDown = () => {
    this.timer();
  }

  stopCountDown = () => {
    clearInterval(this.interval); // Not working
  }

  render() {
    return (
      <div>
        <button onClick={this.startCountDown}>
          Start Countdown
                    </button>
        <p>{this.state.countDown}</p>
      </div>
    );
  }
}

ReactDOM.render(<TestInterval countDown={3} />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>