zoukankan      html  css  js  c++  java
  • raect hook中使用防抖(debounce)和节流(throttle)

    一、基础

      参考以前写的博客:https://www.cnblogs.com/gg-qq/p/11249200.html

    二、react中实现防抖和节流的hooks

      手写可靠的useDebounce:

    export function useDebounce(fn, delay) {
      const { current } = useRef({});
      function f(...args) {
        if (current.timer) {
          clearTimeout(current.timer);
        }
        current.timer = setTimeout(fn.bind(undefined, ...args), delay);
      }
      return f;
    }

      useThrottle:

    export function useThrottle(fn, delay) {
      const { current } = useRef({});
      function f(...args) {
        if (!current.timer) {
          current.timer = setTimeout(() => {
            delete current.timer;
          }, delay);
          fn(...args);
        }
      }
      return f;
    }

     三、创建唯一的debounce,防止重复调用函数

      使用useCallback由于创建之后useCallback从不刷新,它内部的state一直不变 (内部进行setter会改变外部state)

    const load = useCallback(
        debounce(() => loadList(), 500),
        [],
      );

      使用UseRef,保存函数,终身存在

    const load = useRef(
        debounce(() => loadList(), 500),
        [],
      );

     

  • 相关阅读:
    QT1 HelloWorld
    SDL2.0 播放YUV
    vim寄存器
    Makefile模板
    apue初学--DIR
    apue初学--平台的判断
    各种推导式
    文件操作
    list tuple dict set
    字符串和编码
  • 原文地址:https://www.cnblogs.com/gg-qq/p/15338952.html
Copyright © 2011-2022 走看看