You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对多层数组JSON数据使用.map()?Weather API数据访问异常

问题解决:Weather API 预报数据映射返回undefined

核心问题分析

  • API数据层级错误:Weather API返回的forecastday数组嵌套在forecast对象内部,直接访问forecast.forecastday会返回undefined,正确路径是forecast.forecast.forecastday。
  • 字段访问逻辑错误:
    • 单日最高温maxtemp_c属于day对象,并非hour子对象
    • 你请求的是1天的逐小时预报,forecastday是按天分组的数组(仅1个元素),真正的逐小时数据是该元素下的hour数组

修正后的代码

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
    condition: {
        text: string
        icon: string
    }
}

interface Day {
    maxtemp_c: number
    mintemp_c: number
}

interface ForecastDay {
    date: string
    day: Day
    hour: Hour[]
}

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 forecastData = await getHourlyForecast()
  // 提取当天的逐小时数据数组
  const hourlyData = forecastData.forecast.forecastday[0].hour
  // 提取当天的日度预报数据
  const dailyData = forecastData.forecast.forecastday[0].day

  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">
          {hourlyData.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.time).toLocaleString("en-US", { hour: "numeric", hour12: true })}</p>
              <img 
                className="w-16 h-16"
                src={hour.condition.icon}
                alt={hour.condition.text}
                aria-label={hour.condition.text}
              />
              <div>
                {/* 当前小时温度 */}
                <p className="bg-black/25 px-2 italic rounded-xl text-white mb-2">
                  Temp:{" "}
                  <span aria-label={`Current temperature: ${hour.temp_c.toFixed()} degrees Celcius`}>
                    {hour.temp_c.toFixed()}°
                  </span>
                </p>
                {/* 当日最高温 */}
                <p className="bg-black/25 px-2 italic rounded-xl text-white">
                  High:{" "}
                  <span aria-label={`Maximum temperature: ${dailyData.maxtemp_c.toFixed()} degrees Celcius`}>
                    {dailyData.maxtemp_c.toFixed()}°
                  </span>
                </p>
              </div>
            </div>
          ))}
        </div>
    </div>
   
  );
}

额外优化说明

  • 补充了Day和完善了Hour接口,避免类型报错,提升代码严谨性
  • 修正了Tailwind CSS尺寸类(w-50 h-50为非法类,替换为w-16 h-16)
  • 调整时间展示逻辑,逐小时预报显示具体时段而非星期
  • 明确区分逐小时温度与当日最高温的数据源,逻辑更清晰

内容的提问来源于stack exchange,提问作者Tim Barnsley

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 19:17:08