繁体   English   中英

在React Component中使用setInterval

[英]Using setInterval in React Component

我正在阅读官方反应网站上的教程。 在关于生命周期方法的示例中,在componentDidMount方法下,将timerID设置为setInterval函数。

我的问题是,尽管timerID已经初始化,但它从未在整个应用程序中调用过,如果没有在应用程序的任何地方显式调用timerID,应用程序如何工作。 这是下面的代码。

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      date: new Date()
    });
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

ReactDOM.render(
  <Clock />,
  document.getElementById('root')

);

this.timerID是一个数字非零值,用于标识通过调用setInterval()创建的计时器; 可以将此值传递给clearInterval以清除计时器。

所以在componentDidMount中调用setInterval之类的

componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

你想在组件安装的every 1 sec a执行tick()函数。 现在当您导航到另一个组件并且当前组件已卸载时,如果您没有清除tick()函数的间隔调用,它将继续执行。

因此,在componentWillUnmount函数中,清除了计时器,该计时器由setInterval返回的数值标识,该值存储在this.timerID

componentWillUnmount() {
    clearInterval(this.timerID);
  }

所以React文档中提供的完整代码是

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      date: new Date()
    });
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);

这很简单。 一旦React执行componentDidMount()生命周期方法,计时器就会开始运行。

this.timerID = setInterval(
      () => this.tick(),
      1000
    );

上面的计时器将一直运行,直到卸载组件(根据您的代码)。 您的代码以这种方式工作并不奇怪。

在这份反应文件中写道

我们将在componentWillUnmount()生命周期方法中拆除计时器

因此, this.timerID将在componentWillUnmount()生命周期方法中用于停止计时器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM