useUnmount:组件卸载的时候执行
本质是对 useEffect(() => { return () => {} }, []) 进行包装,同时 fn 有可能是动态变化的,因此结合 useLatest hooks 进行获取最新的 fn 函数进行绑定
import { useEffect } from 'react';
import useLatest from '../useLatest';
const useUnmount = (fn: () => void) => {
if (process.env.NODE_ENV === 'development') {
if (typeof fn !== 'function') {
console.error(`useUnmount expected parameter is a function, got ${typeof fn}`);
}
}
const fnRef = useLatest(fn);
useEffect(
() => () => {
fnRef.current();
},
[],
);
};
export default useUnmount;
useMount:组件初始化时执行
本质就是针对 useEffect(() => { xxx }, []) 进行包装
import { useEffect } from 'react';
const useMount = (fn: () => void) => {
if (process.env.NODE_ENV === 'development') {
if (typeof fn !== 'function') {
console.error(`useMount: parameter \`fn\` expected to be a function, but got "${typeof fn}".`);
}
}
useEffect(() => {
fn?.();
}, []);
};
export default useMount;
useUnmountedRef:判断当前组件是否已经卸载
使用 unmountedRef 记录该组件是不是已销毁,useEffect return 函数标记 unmountedRef 为 true
import { useEffect, useRef } from 'react';
const useUnmountedRef = () => {
const unmountedRef = useRef(false);
useEffect(() => {
unmountedRef.current = false;
return () => {
unmountedRef.current = true;
};
}, []);
return unmountedRef;
};
export default useUnmountedRef;