[英]How to throttle this api request using lodash in React
我正在使用 React 並試圖弄清楚如何實現 lodash debounce 方法來限制 api 請求。 我試圖根據互聯網上的示例來實現它,但在這種情況下似乎不起作用。 它應該等待大約 3 秒,然后再根據amountValue
調用 api 方法,這基本上是一個 state 值。 這是我試圖限制 api 請求的代碼。
import debounce from 'lodash/debounce';
const [amountValue, setAmountValue] = useState('');
const handleGetSwapPrice = useCallback(() => {
getFinalPrice(amountValue)
.then((res) => {
const formattedPrice = formatCurrency('USD', res.price);
if (!res.price) {
setIsLoading(true);
} else {
setIsLoading(false);
}
setSwapPrice(formattedPrice);
});
}, [baseAsset, quoteAsset, transactionType]);
useEffect(() => {
handleGetSwapPrice();
}
}, []);
如果您使用 lodash 進行去抖動,則必須使用 useCallback 掛鈎創建 function 的去抖動版本。 如果您在 Input 字段中使用它,請在 handleChange 中提供去抖 function。
import debounce from 'lodash/debounce';
const [amountValue, setAmountValue] = useState('');
const handleGetSwapPrice = () => {
getFinalPrice(amountValue)
.then((res) => {
const formattedPrice = formatCurrency('USD', res.price);
if (!res.price) {
setIsLoading(true);
} else {
setIsLoading(false);
}
setSwapPrice(formattedPrice);
});
}
const debouncedAPICall = useCallback(debounce((e) => handleGetSwapPrice(e), 3000), []);
useEffect(() => {
debouncedAPICall();
}
}, []);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.