【问题标题】:To render auto populated search result Debounce is not working in React and i am not able to call my debounce inside useEffect渲染自动填充的搜索结果 Debounce 在 React 中不起作用,我无法在 useEffect 中调用我的 debounce
【发布时间】:2021-09-08 17:23:08
【问题描述】:

请让我知道我在哪里做错了,因为我是 React 新手,而且我是第一次在现场项目中实现这些概念

这是处理数据的地方

【问题讨论】:

    标签: javascript reactjs react-native react-hooks debouncing


    【解决方案1】:

    我对您的代码有多个注释:

    1. 使用去抖动或节流。但不要一起使用它们。你可以在here找到这两种技术的很好的解释。
    2. 从 useEffect 中删除依赖项。在您的情况下,每次输入更改+每次设置提取时都会执行 useEffect 。从您发布的这段代码中,您实际上没有使用 useEffect 的意义。渲染可以由 useMemo 处理。
    3. useMemo 必须有自己的依赖数组。在您的情况下,它在每次渲染时执行。所以你需要把它的依赖从 useEffect 移到 useMemo。例如你可以做 const inputHasChanged = useMemo(() => debounce(rxCometGetFindUsers, 500), [inputValue]);

    所以要让这个工作你做:

    我之前没有使用过“自动完成”,所以我不确定您必须包含哪些选项。

     return (
        <Autocomplete
          id="find-user"
          className="autoCompSearch"
          style={{ width: 370 }}
          getOptionLabel={option => getValues(option)}
          defaultValue={defaultObj || ""}
          filterOptions={x => x}
          options={options}
          autoComplete
          includeInputInList
          freeSolo
          disableOpenOnFocus
          renderInput={params => (
            <TextField
              {...params}
              placeholder="GLOBAL SEARCH"
              fullWidth
              onChange={handleChange}
              onKeyDown={onKeyDownHandler} // I would remove this, dont see a reason why you would need this and onChange
            />
          )}
    

    这很好

        const handleChange = event => {
    event.preventDefault();
    console.log("User has entered" +event.target.value);
    setInputValue(event.target.value);
     };
    

    接下来,你可以使用lodash 中的debounce 函数,但问题是你可能有一个异步函数,因为你获取了一些东西。 Debounce from lodash 无法处理这种行为。 所以你需要使用p-debounce

    import pDebounce from 'p-debounce';
    
    const inputHasChanged = useMemo(() => pDebounce(rxCometGetFindUsers, 500), [inputValue]);
    
    const rxCometGetFindUsers = async = () =>{
    
    let newData = await ... //do your fetching
    setOptions(newData)
    }
    

    【讨论】:

    • 出现错误:TypeError: func.apply is not a function (anonymous function) 100 | if (timer) clearTimeout(timer) 101 | timer = setTimeout(() => { 102 | timer = null > 103 | func.apply(context, args); | ^ 104 | }, 500) 105 | 106 | }
    • 你能帮我把所有东西放在一起,比如删除 useEffect 并将其代码添加到 useMemo
    • 当然。您从哪里获得“自动完成”组件。是material-ui的那个吗?
    • 是的,只有我得到了这个
    猜你喜欢
    • 2018-05-28
    • 2021-11-06
    • 1970-01-01
    • 2019-04-02
    • 2020-08-30
    • 2019-12-24
    • 2018-03-11
    • 2019-09-01
    • 1970-01-01
    相关资源
    最近更新 更多