自用react 函数组件实现防抖效果遇到的
```react 函数组件使用防抖函数的坑
由于函数组件每次更新时会重新定义函数内部的变量,所有一般的防抖函数在类组件能正常使用的在函数组件上却不正常,达不到应有的效果
例如:
let timer = null
if (timer != null) {
clearTimeout(timer);
console.log(timer);
timer = null;
}
timer = setTimeout( async() => {
let idList: any = [];
if (newData.length > 0) {
newData.map((ite: any) => {
idList.push(ite.id);
});
}
let res = await api.myCommonWordDesc(idList);
if (res.response.code === 0) {
console.log('重新排序成功');
}
}, 5000);
这段代码想要的效果是防止多次请求,但由于是函数组件,效果单单只是延迟请求而已
所以要实现想要的效果,还是要用到 useCallback 钩子或者useRef钩子,
更改:
// 防抖函数,防止用户多次排序而产生多次请求
const useDebounce = (func:any,delay:any)=> {
let timer:any = null;
return (...args) => {
// console.log(timer,"=======");
clearTimeout(timer);
timer = setTimeout(() => {
func(...args);
}, delay);
}
}
const fn = useCallback(useDebounce((value)=>newList(value), 5000), []);