自用react 函数组件实现防抖效果遇到的

自用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), []);

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值