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
相关产品推荐
相关产品推荐

