在卸载组件之前是否真的需要清除计时器? [英] Is it really necessary to clear the timers before unmounting the component?

查看:48
本文介绍了在卸载组件之前是否真的需要清除计时器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常计时器会在从 DOM 卸载组件之前被清除.但是如果我们忘记清除计时器会有什么副作用?

Usually timers will be cleared before unmounting the component from DOM. But what would be the side effects if we forgot to clear the timers?

推荐答案

假设您在某个函数中调用了 timer 并且当您导航到另一个组件并且当前组件已卸载code>,如果你不清除定时器,你的函数会继续执行.

Suppose you call a timer in some function and when you navigate to another component and your current component has unmounted, if you do not clear the timer, your function will continue to be executed.

因此在 componentWillUnmount 函数中,您需要清除可以通过 setInterval 返回的数值识别的计时器

Hence in the componentWillUnmount function you need to clear the timer which can be identified by the numeric value returned by setInterval

React DOCS 中提到的:

AS mentioned in the React DOCS:

componentWillUnmount() 在组件被调用之前立即被调用卸载和销毁.在此方法中执行任何必要的清理,例如使计时器无效、取消网络请求或清理up 任何在 componentDidMount 中创建的 DOM 元素

componentWillUnmount() is invoked immediately before a component is unmounted and destroyed. Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, or cleaning up any DOM elements that were created in componentDidMount

示例:

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

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

副作用:

考虑这样一种情况:您在计时器中进行 API 调用,从中获取您在组件中显示的数据.现在,如果您离开该组件,即使您不需要结果,您通常也不希望一次又一次地调用 API.这将对服务器造成不必要的负载.

Consider a case when in the timer you are making the API call from which you are getting data that you display in your component. Now if you navigate away from the component you wouldn't normally want to be calling the API again and again even though you don't need the result. This will cause and Unnecessary load on the Server.

这篇关于在卸载组件之前是否真的需要清除计时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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