我正在使用 React 在天氣應用程式中作業,但出現此錯誤并且無法解決
“TypeError:oldCities 不可迭代”
這是我的完整代碼:
import React, { useState } from 'react';
import './App.css';
import Nav from './components/Nav';
import Cards from './components/Cards.jsx'
export default function App() {
const [cities, setCities] = useState()
console.log(setCities)
const apiKey = 'api_key'
function onSearch(city){
fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`)
.then(response => response.json())
.then(json => {
if(json.main !== undefined){
const city = {
min: Math.round(json.main.temp_min),
max: Math.round(json.main.temp_max),
id: json.id,
img: json.weather[0].icon,
wind: json.wind.speed,
temp: json.main.temp,
name: json.name,
logitude: json.coord.lon,
latitude: json.coord.lat
};
setCities(oldCities => [...oldCities, city])
}
else{
alert('Ciudad no encontrada')
}
})
.catch(e => console.log(e))
}
return (
<div className="App">
{ /* Tu código acá: */ }
<Nav onSearch={onSearch} />
<Cards cities={cities} />
</div>
);
}
關于如何以不同方式將資料添加到 setCities 的想法?
uj5u.com熱心網友回復:
由于您正在使用 React,我會假設您的代碼如下所示
const [oldCities, setCities] = useState([])
我不確定 oldCities 的用途是什么,但如果你想附加你從 API 呼叫中獲得的城市的 val,它應該是
setCities([...oldCities, new_city ]) // Append to cities array
// Note here to not use oldCities.append
// bc it will preserve the memory address of the array
// and hence not update the component state
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/417656.html
標籤:
上一篇:react中剛剛上傳的渲染檔案
