我试图显示天气API数据从:(https://www.weatherapi.com/api-explorer.aspx#forecast)
import Image from "next/image"
interface Hour {
time_epoch: number
time: string
temp_c: number
temp_f: number
is_day: number
wind_mph: number
wind_kph: number
wind_degree: number
wind_dir: string
pressure_mb: number
pressure_in: number
precip_mm: number
precip_in: number
humidity: number
cloud: number
feelslike_c: number
feelslike_f: number
windchill_c: number
windchill_f: number
heatindex_c: number
heatindex_f: number
dewpoint_c: number
dewpoint_f: number
will_it_rain: number
chance_of_rain: number
will_it_snow: number
chance_of_snow: number
vis_km: number
vis_miles: number
gust_mph: number
gust_kph: number
}
async function getHourlyForecast() {
const location = 'Pemberton'
const apiKey = '84703323c7f94238a98203306233010'
const response = await fetch(`http://api.weatherapi.com/v1/forecast.json?key=${apiKey}&q=${location}&days=1&aqi=no&alerts=no` , {
cache: 'no-cache',})
const data = await response.json()
return data
}
export default async function Forecast() {
const forecast = await getHourlyForecast()
console.log(forecast);
return (
<div>
<h2 className="text-center">Hourly Weather Forecast</h2>
<div className="grid grid-cols-2 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-7 gap-6">
{forecast.forecastday.map((hour, index) =>
(
<div key={index} className="text-center rounded-lg flex flex-col items-center bg-green-950/25 p-10">
<p>{new Date(hour.date).toLocaleString("en-US", { weekday: "short"})}</p>
<img className="w-50 h-50"
src={hour.hour.condition.icon}
alt={hour.hour.condition.text}
aria-label={hour.hour.condition.text}/>
<div>
<p className="bg-black/25 px-2 italic rounded-xl text-white mb-2">
High:{" "}
<span aria-label={`Maximum temperature: ${hour.hour.temp_c.toFixed()} degrees Celcius`}>
{hour.hour.maxtemp_c.toFixed()}°
</span>
</p>
<p className="bg-black/25 px-2 italic rounded-xl text-white">
Low:{" "}
<span aria-label={`Minimum temperature: ${hour.hour.temp_c.toFixed()} degrees Celcius`}>
{hour.hour.temp_c.toFixed()}°
</span>
</p>
</div>
</div>
))}
</div>
</div>
);
}
字符串
我能够Map来自Forecast.Current的数据,但我也想MapForecast.Forecastday.Day对象,但对象返回为未定义。有人可以帮助吗?
已尝试:{forecast.forecastday.map((hour,index)=>但未定义。
2条答案
按热度按时间s6fujrry1#
修改你的代码。
字符串
一个建议-如果这个组件经常使用相同的数据重新渲染,你可以使用React Hook -**
useMemo
**来记住预测数据,避免不必要的重新渲染。请告诉我这是否有效。d4so4syb2#
要Mapforecastday及其嵌套属性,您需要确保每个嵌套级别都存在且未定义。
示例
字符串