【问题标题】:Throttle not working when calling class method from inside throttled function从节流函数内部调用类方法时节流不起作用
【发布时间】:2020-02-13 06:16:34
【问题描述】:

我有这个限制文本输入的代码,但我也希望它限制一个方法调用,该方法调用似乎正在阻止文本限制工作。

import { throttle } from 'lodash';
...
      <input
        type="text"
        onChange={(e): void => throttledTextInput(e.target.value)}
        style={{ outline: 'none' }}
      />
...
  const throttledTextInput = throttle((text) => handleThrottledText(text), 1000);
...
  const handleThrottledText = (text: string): void => {
    console.log(text); // without the below two lines it works fine
    const textInputMessage: Array<Action> = [];
    // but when calling the below, the throttling stops working and it 
  };

我该如何解决这个问题?

【问题讨论】:

  • 这是在功能组件中吗?
  • @Dominic 是的

标签: reactjs typescript lodash throttling


【解决方案1】:

我假设这是在一个功能组件中,因此每次重新渲染组件时都会创建 throttledTextInput,从而破坏它的行为。我猜messagingController.dispatchActions 会导致您的组件重新渲染。

const throttledTextInput = useRef(throttle(handleThrottledText, 1000));

const handleThrottledText = (text: string): void => {
  console.log(text);
};

useRef 只会创建一次节流函数,您可以使用相同的模式进行去抖动等。

这样称呼它:throttledTextInput.current('calling throttled func with this text')

如果您的限制函数具有依赖项,则需要声明它们,以便在它们发生变化时重新创建函数。但要小心,如果受限制的回调本身改变了依赖关系,它将中断,因为函数将不断重新创建。对于这个 useCallback 是一个更合适的钩子:

const throttledTextInput = useCallback(
  throttle(text => {
    console.log('called throttle with', text, props.dispatchMessages);
  }, 1000),
  [props.dispatchMessages]
);

useRef 不同,您只需使用throttledTextInput('some text') 调用它。

【讨论】:

  • 谢谢!这很棒并且修复了限制,但它破坏了我的应用程序的另一部分 - 现在它似乎不会对道具更改做出反应,或者父级不会设置作为道具传递给该组件的状态..
  • 非常感谢,不幸的是,在油门停止工作的情况下,使用useCallback 与完全不使用挂钩的效果相同。我认为这是因为我有 get useCallback 来“监听”作为参数传递给 messagingController.dispatchActions 的函数。
  • 我已经更新了上面的代码,以显示我想用useCallback做些什么
  • 看起来你开始对函数进行两次柯里化(text) =&gt; (): void =&gt; {codesandbox.io/s/crazy-poincare-1g9cd
  • 那是因为 handleThrottledTextResponse 是在每次渲染时创建的,因此依赖关系会发生变化,因此油门回调会被重新创建,您需要将其包装在回调或引用中......钩子的乐趣! const handleThrottledTextResponse = useCallback(() =&gt; {...}, [setTextInputResponses])
猜你喜欢
  • 2020-09-04
  • 2019-09-26
  • 2019-12-12
  • 2015-07-09
  • 2019-10-03
  • 2023-04-04
  • 1970-01-01
  • 2015-05-31
  • 2020-12-03
相关资源
最近更新 更多