【问题标题】:Getting lodash throttle to work with Redux Action让 lodash 节流阀与 Redux Action 一起工作
【发布时间】:2021-07-02 20:33:11
【问题描述】:

我正在使用最新的 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);
    }
  };

【问题讨论】:

    标签: reactjs redux react-redux lodash


    【解决方案1】:

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

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

    请参阅这篇关于在反应中使用 _.debounce() 的博客文章。同样的概念也适用于油门:https://nodeployfriday.com/posts/react-debounce/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-03
      • 2016-03-30
      • 2014-07-14
      • 1970-01-01
      • 2021-07-14
      • 2019-01-16
      相关资源
      最近更新 更多