[英]warnings in react.js project
我是 react.js 初學者,目前我正在做一個貨幣項目,轉換器的功能運行良好,但我收到了一些錯誤和警告。 不太確定如何解決這個問題。 以下是以下錯誤和警告。
警告:收到value
屬性的 NaN。 如果這是預期的,請將值轉換為字符串。 index.js:1
在 App 的 CurrencyRow 的 div 輸入
指定的值“NaN”無法解析,或超出范圍。
//App.js
function App() {
const [currencyOption,setCurrencyOption] = useState([])
const [fromCurrency,setFromCurrency] = useState()
const [toCurrency,setToCurrency] = useState()
const [exchangeRate,setExchangeRate] = useState()
const [amount,setAmount] = useState(1)
const [amountInFrom,setAmountInFrom] = useState(true)
let fromAmount,toAmount
if (amountInFrom){
fromAmount = amount
toAmount = fromAmount * exchangeRate
}else{
toAmount = amount
fromAmount = amount / exchangeRate
}
useEffect ( ()=> {
fetch("https://api.exchangeratesapi.io/latest")
.then(response=>response.json())
.then(response=>{
const firstCurrency = Object.keys(response.rates)[0]
setCurrencyOption([response.base,...Object.keys(response.rates)])
setFromCurrency(response.base)
setToCurrency(firstCurrency)
setExchangeRate(response.rates[firstCurrency])
})
},[])
useEffect ( ()=> {
if (fromCurrency!=null && toCurrency!=null && fromCurrency!=="EUR")
{
fetch("https://api.exchangeratesapi.io/latest")
.then(response=>response.json())
.then(response=>{
const resultCurrency = response.rates[toCurrency]/response.rates[fromCurrency]
setExchangeRate(resultCurrency)
})
}
else if (fromCurrency!=null && toCurrency!=null)
{
fetch("https://api.exchangeratesapi.io/latest")
.then(response=>response.json())
.then(response=>{
setExchangeRate(response.rates[toCurrency])
})
}
},[fromCurrency,toCurrency])
function changeFromAmount(event) {
setAmount(event.target.value)
setAmountInFrom(true)
}
function changeToAmount(event) {
setAmount(event.target.value)
setAmountInFrom(false)
}
return (
<>
<h1>Convert</h1>
<CurrencyRow
currencyOption = {currencyOption}
selectedCurrency = {fromCurrency}
onChangeCurrency = {event=>setFromCurrency(event.target.value)}
amount = {fromAmount}
changeAmount = {changeFromAmount}
/>
<p className="equal">=</p>
<CurrencyRow
currencyOption = {currencyOption}
selectedCurrency = {toCurrency}
onChangeCurrency = {event=>setToCurrency(event.target.value)}
amount = {toAmount}
changeAmount = {changeToAmount}
/>
</>
)
}
export default App
function CurrencyRow(props) {
const {
currencyOption,
selectedCurrency,
onChangeCurrency,
amount,
changeAmount
} = props
return (
<div>
<input type="number" className="input" value = {amount} onChange = {changeAmount}/>
<select value = {selectedCurrency} className="option" onChange={onChangeCurrency}>
{currencyOption.map(option=>(<option key={option} value={option}>{option}</option>))}
</select>
</div>
)
}
export default CurrencyRow
您得到NaN
是因為您的exchangeRate
state 沒有初始值,因此,在第一次渲染時,應用程序嘗試將amount
乘以undefined
導致NaN
作為結果
如果沒有給出所有操作數,您需要為exchangeRate
設置初始值或阻止計算
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.