简体   繁体   English

在 React Native 中卸载组件期间,清理功能在 UseEffect Hook 中不起作用

[英]Cleaning Function not Working in UseEffect Hook During Component Unmount in React Native

In react native app, there are two components A and B in App.js which toggle with k state change.App.js Native 应用程序中, App.js有两个组件AB ,它们会随着k状态变化而切换。

App.js

...

const App = () => {
      const [ k, setK ] = useState(false);

      const toggleK = () => setK(!k);

      if(k) {
            return <A />;
      }else {
            return <B toggleK={toggleK} />;
      }
};
...

In A , setInterval is initialized in useffect .AsetIntervaluseffect初始化。 It calls async function every 10 seconds.它每 10 秒调用一次异步函数。 But when it unmounts on K state change in App.js , the cleaning function is not run (no A unmounting... is logged) and so does the clearInterval .但是当它卸载App.js K状态更改时,不会运行清理功能(没有记录A unmounting... ), clearInterval也是如此。

Any thing I'm doing wrong here?我在这里做错了什么?

...

const A = () => {
      const [ someState, setSomeState ] = useState(...);

      let timer;

      useEffect(() => {
            if(!timer) {
                  timer = setInterval(async () => await run_async_func(), 10000);
            }

            return () => {
                  console.log('A unmounting...');
                  clearInterval(timer);
            };
      }, [ someState ]);
};
...

Try this with useRef().用 useRef() 试试这个。

const A = () => {
 const timer = useRef()
  const [ someState, setSomeState ] = useState(...);


  useEffect(() => {
        if(!timer) {
              timer.current = setInterval(async () => await run_async_func(), 10000);
        }

        return () => {
              console.log('A unmounting...');
              clearInterval(timer.current);
        };
  }, [ someState ]);
};

Resolved the issue解决了问题

  • What was causing the issue?是什么导致了这个问题?

A. Overlooked the someState in useEffect dependency array. A.忽略了someStateuseEffect依赖性阵列。 Basically, cleaner function will only run if any variable in dependency array mutates.基本上,只有在依赖数组中的任何变量发生变异时,更清洁的函数才会运行。 So, I used another useEffect without any dependencies (see below).所以,我使用了另一个没有任何依赖关系的useEffect (见下文)。 Thanks @TayyabMazhar for pointing out this感谢@TayyabMazhar 指出这一点

...
const A = () => {
      const [ someState, setSomeState ] = useState(...);

      let timer;

      useEffect(() => {
            if(!timer) {
                  timer = setInterval(async () => await run_async_func(), 10000);
            }
      }, [ someState ]);

      useEffect(() => {
            return () => {
                 console.log('A unmounting...');
                 clearInterval(timer);
            };
      }, []);
};
...

you can use this hook i create this one你可以使用这个钩子我创造了这个

    import { useEffect, useRef } from 'react';

export const useInterval = (callback: () => void, delay: number): void => {
    const savedCallback = useRef(null);

    // Remember the latest callback.
    useEffect(() => {
        savedCallback.current = callback;
    }, [callback]);

    // Set up the interval.
    useEffect(() => {
        function tick() {
            savedCallback.current();
        }
        if (delay !== null) {
            const id = setInterval(tick, delay);
            return () => clearInterval(id);
        }
    }, [delay]);
};

暂无
暂无

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

相关问题 在 React useEffect hook 中清理 Lodash debounce function - Cleaning up Lodash debounce function in React useEffect hook 如何使用useeffect react hook在组件卸载时删除事件监听器mousedown? - How to remove event listener mousedown on component unmount using useeffect react hook? React Animation无法卸载组件 - React Animation not working on unmount of component 卸载时未运行清理 function 的反应组件。 使用 Firestore - react component not running the cleanup function on unmount. Working with firestore 带有useEffect的自定义react钩子,不能在非组件函数中使用 - Custom react hook with useeffect, cant use in non-component function React Hook &quot;useEffect&quot; 在函数 &quot;shoes&quot; 中调用,它既不是 React 函数组件,也不是自定义 React Hook - React Hook "useEffect" is called in function "shoes" which is neither a React function component or a custom React Hook 反应 setState 钩子不适用于 useEffect - React setState hook not working with useEffect 在包含 useEffect 的组件上调用 API (React Native) 时,cleraInterval () 不起作用 - cleraInterval ()not working when on a component that contains useEffect to call the API (React Native) React Hook “React.useEffect” 在 function “selectmenu” 中调用,它既不是 React function 组件也不是自定义 React Hook ZC1C425268E68385D1AB5074F1477 - React Hook “React.useEffect” is called in function “selectmenu” which is neither a React function component or a custom React Hook function 清理组件状态 useEffect - Cleaning component states useEffect
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM