我想在一個 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.)
uj5u.com熱心網友回復:
所以聽起來你想使用:
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")(例如)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/463198.html
標籤:javascript 反应 钩
上一篇:無法使用函式更新物件
