useUnmount:组件卸载的时候执行

本质是对 useEffect(() => { return () => {} }, []) 进行包装,同时 fn 有可能是动态变化的,因此结合 useLatest hooks 进行获取最新的 fn 函数进行绑定

  1. import { useEffect } from 'react';
  2. import useLatest from '../useLatest';
  3. const useUnmount = (fn: () => void) => {
  4. if (process.env.NODE_ENV === 'development') {
  5. if (typeof fn !== 'function') {
  6. console.error(`useUnmount expected parameter is a function, got ${typeof fn}`);
  7. }
  8. }
  9. const fnRef = useLatest(fn);
  10. useEffect(
  11. () => () => {
  12. fnRef.current();
  13. },
  14. [],
  15. );
  16. };
  17. export default useUnmount;

useMount:组件初始化时执行

本质就是针对 useEffect(() => { xxx }, []) 进行包装

  1. import { useEffect } from 'react';
  2. const useMount = (fn: () => void) => {
  3. if (process.env.NODE_ENV === 'development') {
  4. if (typeof fn !== 'function') {
  5. console.error(`useMount: parameter \`fn\` expected to be a function, but got "${typeof fn}".`);
  6. }
  7. }
  8. useEffect(() => {
  9. fn?.();
  10. }, []);
  11. };
  12. export default useMount;

useUnmountedRef:判断当前组件是否已经卸载

使用 unmountedRef 记录该组件是不是已销毁,useEffect return 函数标记 unmountedRef 为 true

  1. import { useEffect, useRef } from 'react';
  2. const useUnmountedRef = () => {
  3. const unmountedRef = useRef(false);
  4. useEffect(() => {
  5. unmountedRef.current = false;
  6. return () => {
  7. unmountedRef.current = true;
  8. };
  9. }, []);
  10. return unmountedRef;
  11. };
  12. export default useUnmountedRef;