const antiShakeHook = (timing: number) => {
let timeout: any = null;
// 清除定时器,清理变量
function clear() {
clearTimeout(timeout);
timeout = null;
},
function change(callback: () => void) {
clear();
timeout = setTimeout(() => {
callback();
clear();
}, timing)
}
const ref = useRef({
clear,
change
})
useEffect(() => {
// 注销时自动销毁
return clear();
}, [])
return ref.current
}
这个hook传入一个number类型做为倒计时时间,在页面注销阶段销毁hook里的常量
const { change } = antiShakeHook(500);
const onSearch = useCallback((event) => {
change(() => {
setSearchValue(event);
})
}, []);
使用时传入一个数值,结构出change,使用的地方调用把callback传进去就可以