javascript-React:组件停止呈现时函数会发生什么

前端之家收集整理的这篇文章主要介绍了javascript-React:组件停止呈现时函数会发生什么 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我在组件中定义了一个函数,该函数在安装组件时启动并保持运行.当组件停止渲染或卸下时,该函数会发生什么?

class MyComponent extends React.Component<> {
  _count = () => {
    console.log('a second passed');
    setTimeout(1000,this._count);
  }

  componentDidMount() {
    _count();
  }
}
最佳答案
除非清除计时器,否则计时器将一直运行,因此您需要在componentWillUnmount中清除它,该计时器用于“执行任何必要的清理…例如使计时器无效”:

class MyComponent extends React.Component {
  _count = () => {
    console.log('a second passed');
    this.countTimer = setTimeout(this._count,1000);
  }

  componentDidMount() {
    _count();
  }

  componentWillUnmount() {
    clearTimeout(this.countTimer);
  }
}
原文链接:https://www.f2er.com/js/531210.html

猜你在找的JavaScript相关文章