(反应) 使用 useEffect 和 useState 获取数据时"delay"



下面是我的代码。

我正在做的是通过获取外部API的货币转换器应用程序。保证进程.env.REACT_APP_DATA_SOURCE始终正确。

这里的问题是:如果我更改货币,无论是inputCurrency还是outputCurrency,我都需要单击";提交";按钮两次而不是一次以显示正确答案。为什么会这样?

我想不出更好的措辞了,所以我用了";延迟;在标题中。

谢谢!

import './App.css';
import { useState, useEffect } from 'react';
import { Select, Button, ButtonGroup } from '@chakra-ui/react';
function App() {
const [exchangeRate, setExchangeRate] = useState(7.8491);
const [inputCurrency, setInputCurrency] = useState('USD');
const [inputAmount, setInputAmount] = useState(1);
const [outputCurrency, setOutputCurrency] = useState('HKD');
const [outputAmount, setOutputAmount] = useState(7.8491);
useEffect(() => {
const fetchData = async (url) => {
await fetch(url)
.then((response) => response.json())
.then((data) => setExchangeRate(data.conversion_rates[outputCurrency]));
};
try {
let url = `${process.env.REACT_APP_DATA_SOURCE}${inputCurrency}`;
fetchData(url);
} catch (err) {
console.log(err);
}
}, [inputCurrency, outputCurrency]);
const handleSubmit = async (e) => {
e.preventDefault();
setInputCurrency(e.target.inputCurrency.value);
setInputAmount(e.target.inputAmount.value);
setOutputCurrency(e.target.outputCurrency.value);
let result = inputAmount * exchangeRate;
setOutputAmount(result);
};
return (
<div className="main-body">
<form onSubmit={handleSubmit}>
<h3>Set input amount:</h3>
<input className="inputAmount" name="inputAmount" type="number" />
<h3>Set input currency:</h3>
<Select name="inputCurrency">
<option value="USD">USD</option>
<option value="HKD">HKD</option>
<option value="CNY">CNY</option>
<option value="GBP">GBP</option>
<option value="CAD">CAD</option>
</Select>
<h3>Set output currency:</h3>
<Select name="outputCurrency">
<option value="USD">USD</option>
<option value="HKD">HKD</option>
<option value="CNY">CNY</option>
<option value="GBP">GBP</option>
<option value="CAD">CAD</option>
</Select>
<Button colorScheme="blue" type="submit">
Submit
</Button>
</form>
<h3>
{inputAmount} {inputCurrency} is equal to:
</h3>
<h3>
{outputAmount} {outputCurrency}
</h3>
</div>
);
}
export default App;

您在错误的地方计算输出量。首先,更新handleSubmit中的inputCurrencyoutputCurrency。这意味着useEffect将被"触发",并且将获取新的汇率。但这不会马上发生。在计算结果之前肯定不会。

const handleSubmit = async (e) => {
e.preventDefault();
setInputCurrency(e.target.inputCurrency.value);
setInputAmount(e.target.inputAmount.value);
setOutputCurrency(e.target.outputCurrency.value);
//This will ALWAYS use the old previous exchange rate.
let result = inputAmount * exchangeRate;
setOutputAmount(result);
};

只要exchangeRateinputAmount发生变化,您就需要重新计算outputAmount。您可以使用其他useEffect,如:

useEffect(() => {
//Take these out from handleSubmit.
let result = inputAmount * exchangeRate;
setOutputAmount(result);
}, [inputAmount, exchangeRate])

最新更新