【发布时间】:2021-06-27 17:47:43
【问题描述】:
我收到此错误:
1.警告:收到 value 属性的 NaN。如果这是预期的,请将值转换为字符串。
2.警告:列表中的每个孩子都应该有一个唯一的“关键”道具。
这是我的代码:
const BASE_URL = `http://api.exchangeratesapi.io/latest?access_key=${ACCESS_KEY}`
const App = () => {
const [ currencyOptions, setCurrencyOptions ] = useState([]);
const [ fromCurrency, setFromCurrency] = useState()
const [toCurrency, setToCurrency] = useState()
const [exchangeRate, setExchangeRate] = useState()
const [amount, setAmount] = useState(1)
const [amountInFromCurrency, setAmountInFromCurrency] = useState(true)
let toAmount, fromAmount
if (amountInFromCurrency){
fromAmount = amount
toAmount = amount * exchangeRate
} else {
toAmount =amount
fromAmount = amount / exchangeRate
}
useEffect(() => {
fetch(BASE_URL)
.then(res => res.json())
.then(data => {
const firstCurrency = Object.keys(data.rates)[0]
setCurrencyOptions([data.base, ...Object.keys(data.rates)])
setFromCurrency(data.base)
setToCurrency(firstCurrency)
setExchangeRate(data.rates[firstCurrency])
})
}, [])
useEffect(() => {
if (fromCurrency != null && toCurrency != null) {
fetch(BASE_URL)
.then(res => res.json())
.then(data => setExchangeRate(data.rates[toCurrency]))
}
},[fromCurrency,toCurrency])
function handleFromAmountChange(e) {
setAmount(e.target.value)
setAmountInFromCurrency(true)
}
function handleToAmountChange(e) {
setAmount(e.target.value)
setAmountInFromCurrency(false)
}
return (
<>
<h1>Convert</h1>
<CurrencyRow
currencyOptions={currencyOptions}
selectedCurrency={fromCurrency}
onChangeCurrency={e => setFromCurrency(e.target.value)}
onChangeAmount={handleFromAmountChange}
amount = {fromAmount}
/>
<div className="equals"> = </div>
<CurrencyRow
currencyOptions={currencyOptions}
selectedCurrency={toCurrency}
onChangeCurrency={e => setToCurrency(e.target.value)}
onChangeAmount={handleToAmountChange}
amount = {toAmount}
/>
</>
)
}
export default App;
这是 CurrencyRow:
const CurrencyRow = (props) => {
const {
currencyOptions,
selectedCurrency,
onChangeCurrency,
amount,
onChangeAmount
} = props
return (
<div>
<input type="number" className="input" value={amount} onChange={onChangeAmount}/>
<select value={selectedCurrency} onChange={onChangeCurrency}>
{currencyOptions.map(option => (
<option key={option.id} value={option}>{option}</option>
))}
</select>
</div>
)
}
export default CurrencyRow;
【问题讨论】:
-
data.rates[firstCurrency]的值是多少? (在setExchangeRate(data.rates[firstCurrency])内)。它是string还是number? -
option对象是什么样的? -
data.rates[firstCurrency] 的值来自 Api,其中值因国家/地区的货币而异。
-
及其在api中的值为EUR=1
-
当您定义
toAmount和fromAmount时,您可以尝试记录typeofamount和exchangeRate吗?要知道为什么amount是NaN
标签: reactjs