ReactJS:消除具有状态值作为参数的函数;最好的方法是什么?

我已经访问了此链接,并尝试遵循一些示例: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对象并在分派事件时向事件添加属性来做到这一点。它有效,但这是一个好的解决方案吗?有没有更好的方法可以做到这一点?

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

  };
shilaoban2 回答:ReactJS:消除具有状态值作为参数的函数;最好的方法是什么?

由于debounceuseCallback均返回一个函数,因此您可以直接将其传递。

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

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

   handler(argument1,argument2,...args);
};
本文链接:https://www.f2er.com/2863988.html

大家都在问