yk7412 2021-12-19 23:42 采纳率: 50%
浏览 163
已结题

关于react hook防抖函数,函数组件中没有this,但是函数中用到了this

函数的功能实现了,但是不太理解其中原理

这是网上找的案例,基本上大同小异,有几点疑问
1、定时器中为什么要使用fn.call(this,args),使用this的意义是什么
2、args是什么,从哪来的
2、return的函数 f 与 fn 的关系,为什么需要把 f 的参数args传给fn

function useDebounce(fn, delay, dep = []) {
  const { current } = useRef({ fn, timer: null });
  useEffect(function () {
    current.fn = fn;
  }, [fn]);
 
  return useCallback(function f(args) {
    if (current.timer) {
      clearTimeout(current.timer);
    }
    current.timer = setTimeout(() => {
      current.fn.call(this, args);
    }, delay);
  }, dep)
}
  • 写回答

1条回答 默认 最新

  • 关注

    箭头函数内没有自己的this。如果在箭头函数内使用this,访问的是外层函数的this。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 1月1日
  • 已采纳回答 12月24日
  • 创建了问题 12月19日