在React类中清除间隔 [英] Clear interval in React class

查看:90
本文介绍了在React类中清除间隔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我们有这个简单的React组件,它从父组件接收一个整数。单击该按钮时,我们将在屏幕上显示整数,然后开始倒数计时。

So, we have this simple React component that receives an integer from the father component. When the button is clicked, we display the integer on the screen and the countdown begins.

问题是如何停止倒数计时。在阅读其他SO帖子时,我发现了有关clearInterval()的信息,但似乎这里缺少一些内容。

The question is how can I stop the countdown. While reading other SO posts, I found about clearInterval(), but it seems I am missing something here.

任何帮助将不胜感激。如果有人足够友好地向我解释为什么示例代码无法按预期工作,则将获得额外的奖励积分。

Any help would be greatly appreciated. Bonus appreciation points will be awarded if someone is kind enough to explain to me why the sample code is not working as expected.

    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 返回的间隔引用。

文档

You need to store the interval reference returned from setInterval.
From the docs:


它返回一个间隔唯一标识间隔的ID,因此
您可以稍后通过调用clearInterval()将其删除。

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

因此,您的代码应例如:

So your code should look like that for example:

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

然后清除它:

 clearInterval(this.interval);

我会在状态真正设置后检查条件( setState 是异步的),您可以在 setState 的回调中完成。

I would check the condition after the state has truly set (setState is asynchronous) you can do it inside the callback of 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>

这篇关于在React类中清除间隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆