1.useMount
只在组件初始化时执行的 Hook。
const useMount = (fn: () => void) => {
if (process.env.NODE_ENV === 'development') {
if (!isFunction(fn)) {
console.error(
`useMount: parameter \`fn\` expected to be a function, but got "${
typeof fn}".`,
);
}
}
useEffect(() => {
fn?.();
}, []);
};
export default useMount;
2.useUnmount
在组件卸载(unmount)时执行的 Hook。
import {
useEffect } from 'react';
import useLatest from '../useLatest';
import {
isFunction } from '../utils';
const useUnmount = (fn: () => void) => {
if (process.env.NODE_ENV === 'development') {
if (!isFunction(fn)) {
console.error(`useUnmount expected parameter is a function, got ${
typeof fn}`);
}
}
// !保证函数变化时,函数始终是最新的
const fnRef = useLatest(fn);
useEffect(
() => () => {
fnRef.current();
},
[],
);
};
export default useUnmount;
2.1 useLatest
返回当前最新值的 Hook,可以避免闭包问题。等价于useRef,不同的是该hook直接返回最新的值。useRef需要.current
import {
useRef } from 'react';
function useLatest<T>(value: T) {
const ref = useRef(value);
ref.current = value;
return ref;
}
export default useLatest;
3. useUnmountedRef
获取当前组件是否已经卸载的 Hook。应用场景:组件卸载时取消请求等
import {
useEffect, useRef } from 'react';
// ! unmountedRef.current 代表组件是否已经卸载
const useUnmountedRef = () => {
const unmountedRef = useRef(false);
useEffect(() => {
unmountedRef.current = false;
return () => {
unmountedRef.current = true;
};
}, []);
return unmountedRef;
};
export default useUnmountedRef;