[英]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.