我怎样才能有动态功能来传递去抖动功能

How can I have dynamic function to pass in debounce function

我想在一个 React 组件中实现不同的 api 搜索,并且我使用自定义挂钩。

 const { request:requestOne, data, loading} = useApi(searchOneApiConfig);
 const { request:requestTwo, data, loading} = useApi(searchTwoApiConfig);
 const { request:requestThree, data, loading} = useApi(searchThreeApiConfig);

现在我必须使用 useCallback(debounce... 为每个像:

const SearchLazyQueryOne = useCallback(debounce(requestOne, DEBOUNCED_TIME, LazyQueryConfig), []);
const SearchLazyQueryTwo = useCallback(debounce(requestTwo, DEBOUNCED_TIME, LazyQueryConfig), []); 
const SearchLazyQueryThree = useCallback(debounce(requestThree DEBOUNCED_TIME, LazyQueryConfig), []);

我的问题是如何才能拥有单个“searchLazyQuery”并传递动态请求函数?

(我正在使用 Lodash 的 debounce。)

听起来你想使用:

searchLazyQuery(requestTwo, /*...args*/)

...同时消除对 requestTwo 的调用。这将需要跟踪去抖功能并使用匹配的功能(或根据需要创建一个)。

您可以将函数的去抖动版本存储在 Map 中。这是执行此操作的挂钩草图:

const useDynamicDebounce = (debouncedTime, config) => {
    // Using a ref to provide a stability guarantee on the function we return
    const ref = useRef(null);
    if (!ref.current) {
        // A map to keep track of debounced functions
        const debouncedMap = new Map();
        // The function we return
        ref.current = (fn, ...args) => {
            // Get the debounced version of this function
            let debounced = debouncedMap.get(fn);
            if (!debounced) {
                // Don't have one yet, create it
                debounced = debounce(fn, debouncedTime, config);
                debouncedMap.set(fn, debounced);
            }
            // Do the call
            return debounced(...args);
        };
    }
    return ref.current;
};

在您的组件中使用它:

const searchLazyQuery = useDynamicDebounce(DEBOUNCED_TIME, LazyQueryConfig);

然后使用searchLazyQuery(requestTwo, "args", "for", "requestTwo")(例如)。