让 lodash throttle 与 Redux Action 一起工作

Getting lodash throttle to work with Redux Action

我正在使用最新的 Redux 工具包,我正在尝试限制 keydown 和 keyup 操作,但我不明白为什么它不起作用...我感觉它与调度有关,但我也尝试过限制发送,但没有成功。

这不可能吗?

  // this does NOT get throttled
  const handleOnKeyDown = (e) => {
    e.persist();
    if (e.key === 'ArrowUp') {
      dispatch(setSelectedPage(pageAbove)); // not throttled
    } else if (e.key === 'ArrowDown') {
      dispatch(setSelectedPage(pageBelow)); // not throttled
    }
  };

  // this DOES get throttled
  const handleOnKeyDown = (e) => {
    e.persist();
    console.log('test');
  };

  const throttledOnKeyDown = _.throttle(handleOnKeyDown, 1000);

我也尝试了以下方法,但这也不起作用:

  const throttleSetSelectedPage = _.throttle((param) => dispatch(setSelectedPage(param)), 1000);

  const handleOnKeyDown = (e) => {
    e.persist();
    if (e.key === 'ArrowUp') {
      throttleSetSelectedPage(pageAbove);
    } else if (e.key === 'ArrowDown') {
      throttleSetSelectedPage(pageBelow);
    }
  };

您需要将 _.throttle() 包装在 useCallback() 挂钩中。

在 React 功能组件中,函数主体在每次渲染时都会被调用,因此行 const throttledOnKeyDown = _.throttle(handleOnKeyDown, 1000); 在每次渲染时都会被调用,并创建 _.throttle() 函数的新实例,因此它永远无法到达它的稳定时间。 useCallback 记忆该函数,以便您从一个渲染到下一个渲染获得相同的实例。

请参阅此博客 post,了解如何在 React 中使用 _.debounce()。同样的概念适用于油门:https://nodeployfriday.com/posts/react-debounce/