【问题标题】:Why does lodash throttle not work within the useWindowSize custom hooks?为什么 lodash 油门在 useWindowSize 自定义挂钩中不起作用?
【发布时间】:2022-01-22 21:55:58
【问题描述】:

我正在尝试使用带油门的调整大小事件。但是,它不起作用。我尝试如下调试:

import {throttle} from 'lodash'

export function useWindowSize() {
  const [windowSize, setWindowSize] = useState({
    width: undefined,
    height: undefined,
  })

  const handleResize = () => {
    // handle resize code....
  }

  const onWindowResize = () => {
    console.log('Throttle') // <-- this does print out
    throttle(() => {
      console.log('bam') // <-- this doesn't print out
    }, 100)
  }

  useEventListener('resize', onWindowResize)

  return windowSize
}

从上面的代码中可以看出,在使用来自lodashthrottle 函数之前,我一直在尝试注销。它会打印出来,但throttle 本身的日志不会。有谁知道这可能是为什么以及如何解决这个问题?

【问题讨论】:

    标签: javascript reactjs lodash


    【解决方案1】:

    您的内联函数会在每次渲染时重新生成。只需确保油门功能在下一次渲染时将是相同的功能。你可以使用 useCallback 钩子。

    export function useWindowSize() {
       const [windowSize, setWindowSize] = useState({
         width: undefined,
         height: undefined
      });
      const someFunction = (e) => {
         console.log("bam", e); // 
      };
      const throttleFn = useCallback(throttle(someFunction, 1000), []);
    
      const onWindowResize = (e) => {
         console.log("Throttle", e); 
         throttleFn(e);
      };
    
      useEventListener("resize", onWindowResize);
    
      return windowSize;
    }
    

    【讨论】:

    • 非常感谢。这样效果更好!
    【解决方案2】:

    我一直在尝试解决这个问题,类似于以下代码的东西对我有用:

    export function useWindowSize() {
      const [windowSize, setWindowSize] = useState({
        width: undefined,
        height: undefined,
      })
    
      const handleResize = useCallback(() => {
        console.log('handleResize') // It does log this out
        // handle the resize...
      }, [windowSize])
    
    
      useEventListener('resize', throttle(handleResize, 4000)) // call it here instead
      return windowSize
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-11
      • 2021-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-11
      • 2022-12-22
      相关资源
      最近更新 更多