useLockCallback 和 useCallback用法一致,使用ref标记防止并发执行
import { useCallback, useRef } from 'react';
export default function useLockCallback<T extends (...args: any[]) => any>(callback: T, deps: DependencyList) {
const lock = useRef(false);
return useCallback(async (...args) => {
if (lock.current) return;
lock.current = true;
try {
const req = await callback(...args);
lock.current = false;
return req;
} catch (e) {
lock.current = false;
throw e;
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps);
}
网友评论