react useEffect cleanup



我正在努力理解这个钩子:https://usehooks.com/useOnClickOutside/钩子看起来像这样:

import { useState, useEffect, useRef } from 'react';
// Usage
function App() {
// Create a ref that we add to the element for which we want to detect outside clicks
const ref = useRef();
// State for our modal
const [isModalOpen, setModalOpen] = useState(false);
// Call hook passing in the ref and a function to call on outside click
useOnClickOutside(ref, () => setModalOpen(false));
return (
<div>
{isModalOpen ? (
<div ref={ref}>
👋 Hey, I'm a modal. Click anywhere outside of me to close.
</div>
) : (
<button onClick={() => setModalOpen(true)}>Open Modal</button>
)}
</div>
);
}
// Hook
function useOnClickOutside(ref, handler) {
useEffect(
() => {
const listener = event => {
// Do nothing if clicking ref's element or descendent elements
if (!ref.current || ref.current.contains(event.target)) {
return;
}
handler(event);
};
document.addEventListener('mousedown', listener);
document.addEventListener('touchstart', listener);
return () => {
document.removeEventListener('mousedown', listener);
document.removeEventListener('touchstart', listener);
};
},
// Add ref and handler to effect dependencies
// It's worth noting that because passed in handler is a new ...
// ... function on every render that will cause this effect ...
// ... callback/cleanup to run every render. It's not a big deal ...
// ... but to optimize you can wrap handler in useCallback before ...
// ... passing it into this hook.
[ref, handler]
);
}

我的问题是,我的useEffect中的清理函数将在什么时候运行。我读了";当它的组件卸载时";。但我不知道这意味着什么,它们意味着什么成分。

我的useEffect中的清理函数将在什么时候运行

来自React Docs - When exactly does React clean up an effect?

React在组件卸载时执行清理。然而,正如我们前面学习过,效果会在每次渲染中运行,而不仅仅是一次。这这就是为什么React还会清理之前渲染的效果下次运行效果。

简而言之,清除功能在以下情况下运行:

  • 组件卸载
  • 再次运行useEffect之前

我读到了";当它的组件卸载时";。但我不知道这意味着什么,它们意味着什么成分。

它们指的是使用此钩子的组件。在您的情况下,这是App组件。

最新更新