【问题标题】:Example to add debounce to autocomplete Ant Design为自动完成 Ant Design 添加去抖动的示例
【发布时间】:2020-07-10 12:04:08
【问题描述】:

我在这里需要一些帮助,我是新手,我有这个疑问。

我没有得到一个使用debounce 自动完成的工作示例。即我的 AutoComplete 组件在显示输入的文本时出现延迟,当我为此搜索解决方案时,我知道我们可以通过使用带有 debounce 的 AutoComplete 来克服这个问题。所以请任何人都可以通过向给定的沙箱链接添加去抖动来帮助解决这个问题,或者可以向我建议为什么它在显示输入的文本时会延迟。谢谢。

参考:https://codesandbox.io/s/crazy-galois-5v1mi

【问题讨论】:

  • 我在代码沙箱中看不到延迟。顺便说一句,去抖动实际上会造成延迟,所以我不太明白,因为这个 please anyone can help with this by adding debounce 与这个 can suggest to me why it is delaying 矛盾

标签: reactjs lodash antd debounce


【解决方案1】:

使用 lodash 中的 debounce 方法。

import debounce from 'lodash/debounce';

<AutoComplete
  ...,
  onSearch={debounce(handleSearch, 300)} // 300 is your required delay
/>

【讨论】:

    【解决方案2】:

    添加去抖动内联通常会导致每次击键时触发。 如果你想在用户完成击键后去抖动,那么你需要使用useCallback

    例子-

    const debouncedSearch = useCallback(
        debounce(nextValue => onSearch(nextValue), 1000),
        [], // will be created only once initially
    );
    
    const handleSearch = event => {
        event.persist();
        const { value: nextValue } = event.target;
        // Even though handleSearch is created on each render and executed
        // it references the same debouncedSearch that was created initially
        debouncedSearch(nextValue);
    };
    
    <AutoComplete
      ...,
      onSearch={handleSearch}
    />
    

    我发现这篇文章很有用,值得推荐阅读。 https://www.freecodecamp.org/news/debounce-and-throttle-in-react-with-hooks/

    【讨论】:

      猜你喜欢
      • 2020-11-25
      • 2023-03-22
      • 1970-01-01
      • 2021-08-04
      • 1970-01-01
      • 2020-01-26
      • 1970-01-01
      • 2011-12-24
      • 2023-02-09
      相关资源
      最近更新 更多