从节流函数内部调用类方法时,节流阀不起作用

时间:2019-10-16 12:51:19

标签: reactjs typescript lodash throttling

我有这段代码可以限制文本输入,但是我也希望它限制方法调用,这似乎正在阻止文本限制工作。

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 
  };

任何想法为何?我该如何解决这个问题?预先感谢!

1 个答案:

答案 0 :(得分: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')来称呼它。