如何等到定义了参数后再进行调用



我正在为我的投资组合构建一个React加密货币项目,我只是想知道如何解决api调用采用空参数的问题。正如您可能看到的,我在组件渲染时轮询数据,但是,我在控制台中看到参数为null的错误。我想让api请求等待,直到参数实际上不为空,才能发出api请求。这是我的代码和url,它为要使用的货币返回一个空值:

/api/v1/private/quote?pair=null/null&side=BUY&amount=
谢您的帮助。谢谢

对于handleGetSwapPrice函数,可以使用useMemouseCallback(首选useCallback(。

像这样:

const handleGetSwapPrice = useCallback(() => {
const amountValue = TRANSACTION_TYPES.BUY ? amountState.fromCurrencyAmount : amountState.toCurrencyAmount;
getSwapPrice(`${baseAsset}/${quoteAsset}`, transactionType, amountValue)
.then((res) => {
const formattedPrice = formatCurrency('USD', res.price);
setSwapPrice(formattedPrice);
});
}, [baseAsset, quoteAsset, transactionType, amountState]);

由于您从useEffect调用该函数,因此需要使这些变量成为它的依赖项:


useEffect(() => {
if (isLoggedIn && baseAsset && quoteAsset) {
getSwapPairs()
.then((res) => {
setSwapInfo(res.markets);
if (transactionType === TRANSACTION_TYPES.BUY) {
setSelectedCurrencyState({ ...selectedCurrencyState, selectedFromCurrency: localStorage.getItem('fromCurrency') || 'USD', selectedToCurrency: 'BTC' || localStorage.getItem('toCurrency') });
}
setTransactionType(localStorage.getItem('transactionType', transactionType) || TRANSACTION_TYPES.BUY);
});
const timer = setInterval(handleGetSwapPrice, 6000);
return () => clearInterval(timer);
}
}, [baseAsset, quoteAsset]);

最新更新