简体   繁体   English

useEffect 清理函数

[英]useEffect cleanup function

I use the Usage Effect to implement cancellation.我使用 Usage Effect 来实现取消。 Accordingly, there is a delay, which is carried out in debounce.因此,存在延迟,这是在去抖动中执行的。 The use effect, as I understand it, makes the information leak and an empty function.使用效果,按照我的理解,是信息泄露,空函数。 How to make it so that if there is no "cost" State, then the function will not work and there will be no warning如何使它如果没有“成本”状态,则该功能将不起作用并且不会发出警告

Mistake:Warning: It is not possible to update the reaction state for the unmounted component.错误:警告:无法更新已卸载组件的反应状态。 This is not an operation, but it indicates a memory leak in your application.这不是一个操作,但它表明您的应用程序中存在内存泄漏。 To fix this, cancel all subscriptions and asynchronous tasks in the usage effect cleanup function.要解决此问题,请取消使用效果清理功能中的所有订阅和异步任务。

Code:代码:

    function useDebounce(value,fn, delay) {
      useEffect(() => {
          const handler = setTimeout(() => { fn() }, delay);
          return () => {  clearTimeout(handler) };
        },[value]);
    }

You can create a mounted check.您可以创建一个挂载检查。

function useDebounce(value,fn, delay) {
  useEffect(() => {
    let mounted = true;
    const handler = setTimeout(() => {
       if (mounted) fn();
    }, delay);
    return () => {
      mounted = false;
      clearTimeout(handler);
    };
  },[value]);
}

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

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