【发布时间】:2021-11-08 10:27:30
【问题描述】:
我正在使用 ReactJS 制作天气应用程序,而对于天气,我正在使用 OpenWeatherMap API。我已经提取了一个数组和一个对象,因为它们是我感兴趣的。数组包含天气的种类,如下雨或晴天,对象包含温度。我已经能够从数组中提取天气并将其显示在屏幕上,但我无法从对象中提取温度。控制台从未给出任何错误。这是代码:
import React, {useState,useEffect} from 'react'
function WeatherDisplay()
{
const APIKey = "myKey";
const [weather, setWeather] = useState([]);
const [temperature, setTemperature] = useState([]);
useEffect(() => {
fetchWeather() ;
} , []);
const fetchWeather = async () => {
const data = await fetch(
"https://api.openweathermap.org/data/2.5/weather?q=Islamabad&units=metric&appid=" + APIKey
);
const weather = await data.json();
//console.log(weather.weather);
setWeather(weather.weather);
console.log(weather.main);
setTemperature(weather.main);
}
return(
<section id="w-d-p">
<div style={
{
backgroundColor:"rgba(43, 42, 42, 0.575)",
width:"100%",
height:"100%",
display:"flex",
flexDirection:"column",
justifyContent:"center",
alignItems:"center"
}
} className="container-fluid">
<div style={
{
display:"flex",
flexDirection:"column",
justifyContent:"center",
alignItems:"center"
}
} className="col-sm-12">
<h2 id="city">Islamabad</h2>
{weather.map(main => (
//<h2 key={main.id} id="temp">{main.temp}C</h2>
console.log(main.temp)
))}
{weather.map(weather => (
<h2 key={weather.id} id="weather">{weather.main}</h2>
))}
</div>
</div>
</section>
)
}
export default WeatherDisplay
抱歉,我不得不删除 API 密钥。
现在在console.log() 之前的return()
它会在控制台中显示温度。我注释掉了 h2 标记并将console.log() 放在那里,现在,控制台给出undefined,然后在下一行打印整个对象,然后在下一行再次打印undefined。
所以我发现我没有正确执行map()。请问,我该如何解决这个问题?
这是对象:
main {
"temp": 28.24,
"feels_like": 31.43,
"temp_min": 28.24,
"temp_max": 28.24,
"pressure": 1005,
"humidity": 72,
"sea_level": 1005,
"grnd_level": 947
}
还有一件事,我给useState()打了两次电话,可以吗?或者这也可以改进?谢谢!
【问题讨论】:
标签: reactjs react-hooks openweathermap