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

React/Next.js渲染API JSON数据时map()报错:current.map is not a function

解决React/Next.js中调用天气API后map()报错的问题

问题原因

你调用WeatherAPI的current.json接口返回的是单个对象,不是数组。map()函数仅能用于遍历数组,直接在对象上调用就会抛出TypeError: current.map is not a function错误。

该接口返回的结构大致如下:

{
  "location": {
    "name": "London",
    "region": "City of London, Greater London",
    // 其他location相关字段
  },
  "current": {
    "humidity": 77,
    // 其他current相关字段
  }
}

你的代码里const current = await getCurrentData();拿到的是整个上述对象,并非数组,自然无法用map遍历。

修复代码

直接渲染对象中的对应属性即可,无需使用map:

const getCurrentData = async () => {
    const res = await fetch("http://api.weatherapi.com/v1/current.json?key=84703323c7f94238a98203306233010&q=London&aqi=no")
    return res.json();
};

export default async function Weather() {
    const data = await getCurrentData();
    return (
        <>
            <div>
                <span>{data.location.name}</span>
                <span>{data.current.humidity}</span>
            </div>
        </>
    );
}

如果需要处理多个城市

若要展示多个城市的天气数据,需先将多个城市的API请求结果收集到数组中,再用map遍历:

const getCurrentData = async (city: string) => {
    const res = await fetch(`http://api.weatherapi.com/v1/current.json?key=84703323c7f94238a98203306233010&q=${city}&aqi=no`)
    return res.json();
};

export default async function Weather() {
    // 收集多城市天气数据到数组
    const cities = ["London", "Paris", "New York"];
    const weatherData = await Promise.all(cities.map(city => getCurrentData(city)));
    
    return (
        <>
            {weatherData.map((data, index) => (
                <div key={index}>
                    <span>{data.location.name}</span>
                    <span>{data.current.humidity}</span>
                </div>
            ))}
        </>
    );
}

内容的提问来源于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.07 00:15:05