1

我已经访问了这个链接并尝试了一些例子:在 React.js 中执行去抖动

一点上下文:我正在构建一个我想在 NPM 上部署的搜索框。每次用户键入时,onSearch都会调用一个 prop 函数。这允许程序员根据需要获取新数据。

问题:输入的每个字符都会触发 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("");

经过各种尝试,我终于找到了解决方案。回想过去我是如何消除窗口调整大小事件的,我遵循了或多或少相同的模式。我通过将事件侦听器附加到窗口对象并在调度事件时向事件添加属性来做到这一点。它有效,但它是一个好的解决方案吗?有没有更好的方法来实现这一目标?

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

  };
4

1 回答 1

4

由于两者都debounce返回useCallback一个函数,因此您可以直接传递它。

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

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

   handler(argument1, argument2, ...args);
};
于 2019-12-25T07:08:22.630 回答