ReactJS:去抖一个以状态值作为参数的函数;最好的方法是什么?

ReactJS: debounce a function that has as an argument a state value; what's the best way to do it?

我已经访问过此 link 并尝试遵循一些示例:Perform debounce in React.js

一些背景知识:我正在构建一个搜索框,我想将其部署在 NPM 上。每次用户输入时,都会调用一个 prop 函数 onSearch。这允许程序员在需要时获取新数据。

问题:输入的每个字符都会触发 onSearch,但这不是最佳选择,所以我想消除它。

我想按照其中一篇帖子的建议去做:

import React, { useCallback } from "react";
import { debounce } from "lodash";

const handler = useCallback(debounce(someFunction, 2000), []);

const onChange = (event) => {
    // perform any event related action here

    handler();
 };

我的问题是我需要向 "someFunction" 传递一个参数,该参数是一个状态(字符串):

const [searchString, setSearchString] = React.useState("");

经过各种尝试终于找到了解决办法。记得我过去是如何对 window 调整大小事件进行去抖动的,我或多或少遵循了相同的模式。我通过将事件侦听器附加到 window 对象并在分派事件时向事件添加 属性 来做到这一点。它有效,但它是一个好的解决方案吗?有没有更好的方法来实现这个?

  React.useEffect( ()=> {

    // This will contain the keyword searched when the event is dispatched (the value is stored in event.keyword)
    // the only function dispatching the event is handleSetSearchString
    // It's declared at this level so that it can be accessed from debounceDispatchToParent
    let keyword = "";

    // This function contains the onSearch function that will be debounced, inputDebounce is 200ms
    const debounceDispatchToParent = debounce(() =>
      onSearch(keyword,  isCached("search-keyword-" + keyword)), inputDebounce);

    // This function sets the keyword and calls debounceDispatchToParent
    const eventListenerFunction = (e) => {
      // the event has a property attached that contains the keyword
      // store that value in keyword
      keyword = e.keyword;
      // call the function that will debounce onSearch
      debounceDispatchToParent();
    }

    // Add the listener to the window object
    window.addEventListener("dispatchToParent", eventListenerFunction, false);

    // Clean up
    return ()=> window.removeEventListener("dispacthToParent", eventListenerFunction);
  }, []);

然后每次用户键入我调用 handleSetSearchString:

  const handleSetSearchString = keyword => {

    keyword = keyword.toLowerCase();
    // If the string is longer than the minimum characters required to trigger a filter/search
    if (keyword.length > minChars) {
      // Here I create the event that contains the keyword
      const event = new Event("dispatchToParent");
      event.keyword = keyword;
      window.dispatchEvent(event);

    } else if (keyword.length === 0) {
      // If the string is empty clear the results
      setFilteredItems([]);
    }
    setSearchString(keyword);

  };

因为 debounceuseCallback return 都是一个函数,你可以直接传递它。

const handler = useCallback(debounce(someFunction, 2000), []);

const onChange = (event) => {
   // perform any event related action here

   handler(argument1, argument2, ...args);
};