React自定义hook 给异步函数增加竞态锁,防止并发执行。
2022-01-12 本文已影响0人
学生黄哲
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);
}