Life cycle
useUnmount
用于组件卸载时执行的 Hook
用法
组件卸载时执行。
源码
import { useEffect } from 'react';
import useLatest from '../useLatest';
import { isFunction } from '../utils';
import isDev from '../utils/isDev';
const useUnmount = (fn: () => void) => {
if (isDev) {
if (!isFunction(fn)) {
console.error(`useUnmount expected parameter is a function, got ${typeof fn}`);
}
}
const fnRef = useLatest(fn);
useEffect(
() => () => {
fnRef.current();
},
[],
);
};
export default useUnmount;关于 useLatest,可以查看对应文档:useLatest,用来返回最新的值。
解读
先是环境判断,开发模式下传入参数的类型不为 Function 时,输出错误日志。
然后,主要逻辑就是上面高亮的 15-17 行,用 useEffect 包了一层,然后再将入参函数的执行结果返回。
Last updated on