簡體   English   中英

反應使用效果清理

[英]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 中的清理 function 將在什么時候運行。 我讀了“當它是組件卸載時”。 但我不完全知道這意味着什么,它們是什么意思。

我的 useEffect 中的清理 function 將在什么時候運行

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

React 在組件卸載時執行清理。 然而,正如我們之前所了解的,效果會為每次渲染運行,而不僅僅是一次。 這就是為什么 React 還會在下次運行效果之前清理上一次渲染中的效果。

簡而言之,清理 function 在以下情況下運行:

  • 組件卸載
  • 在再次運行useEffect之前

我讀了“當它是組件卸載時”。 但我不完全知道這意味着什么,它們是什么意思。

它們表示您使用此鈎子的組件。 在您的情況下,這就是App組件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM