最初它显示数据,但在搜索时给出此错误“未处理的拒绝(类型错误):无法读取未定义的属性'lon'”。 请帮忙!
const First = () => {
const [city, setcity] = useState(null);
const [search, setsearch] = useState("mumbai");
const [longitude, setlongitude] = useState("");
useEffect(() => {
const fetchapi = async () => {
const url = `http://api.openweathermap.org/data/2.5/weather?q=${search}&units=metric&appid={API_key}`;
const response = await fetch(url);
const resjson = await response.json();
console.log(resjson.coord.lon);
setlongitude(resjson.coord.lon);
setcity(resjson.main);
}
fetchapi();
}, [search]);
return (
<div className="first">
<div className="App">
<h1>WEATHER APP 1</h1>
<input type="search" className="input" value={search} onChange={(event) => { setsearch(event.target.value) }} />
{!city ? (<p>no data found</p>) :
(
<>
<div className="info">
<h2 className="location">{search}</h2>
<h3 className="temp">{city.temp}° cel</h3>
<h3 className="minmx">Min : {city.temp_min}° cel | Max : {city.temp_max}° cel</h3>
<h1>des</h1>
<h4>longitude : {longitude}</h4>
</div>
</>
)}
</div>
</div>
)
} 导出默认优先