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

ReactJS Fetch报错:Cannot read property 'map' of undefined,如何获取雅虎天气数据?

嘿,我来帮你捋清楚这个问题!首先得给你提个关键信息:你用的这个雅虎天气API其实早就停止服务了——这很大概率是你遇到那个Cannot read property 'map' of undefined错误的根源,不过咱们还是一步步拆解,先搞懂原本的逻辑,再给你可行的解决方案。

一、先搞懂你报错的核心原因

这个错误本质是:你代码里尝试对一个undefined的值调用map方法。也就是说,你假设某个数组(比如预报列表)存在,但实际上接口返回的JSON里根本没有这个字段,或者你访问数据的路径写错了。

现在访问你提供的API链接,会直接返回错误:

{"error":{"lang":"en-US","description":"Not Found"}}

这说明雅虎早就把这个API下线了,自然返回不了你预期的天气数据,你代码里要访问的嵌套属性(比如预报数组)全都是undefined,调用map的时候自然就报错了。

二、假设API还能用的情况下,正确获取temp和icon的方式

如果这个API还在运行,你需要按正确的嵌套路径提取数据,同时必须做空值检查,避免踩undefined的坑。这里给你写个示例(用JavaScript的fetch):

fetch('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text=%22auckland%22)&format=json&env=store://datatables.org/alltableswithkeys')
  .then(res => res.json())
  .then(data => {
    // 用可选链操作符逐层检查,避免取到undefined
    const channel = data?.query?.results?.channel;
    if (!channel) {
      console.error('API返回结构不对,找不到核心数据');
      return;
    }

    // 获取当前温度和图标
    const currentCondition = channel.item?.condition;
    if (currentCondition) {
      const currentTemp = currentCondition.temp; // 注意雅虎返回的是华氏度
      const currentIcon = currentCondition.icon; // 图标是代码,需要对应雅虎的图标地址
      console.log(`当前温度:${currentTemp}°F,图标代码:${currentIcon}`);
    }

    // 如果要处理未来预报列表,先确认是数组再调用map
    const forecastList = channel.item?.forecast;
    if (Array.isArray(forecastList)) {
      const processedForecast = forecastList.map(item => ({
        date: item.date,
        high: item.high,
        low: item.low,
        icon: item.icon
      }));
      console.log('未来预报数据:', processedForecast);
    } else {
      console.error('预报列表不存在,或者不是数组');
    }
  })
  .catch(err => console.error('请求API失败:', err));

这里的关键是用了?.可选链操作符,它会在访问嵌套属性时,如果中间某个属性是undefined或null,就直接返回undefined,不会抛出错误;另外在调用map前,用Array.isArray()确认目标是数组,彻底避免报错。

三、可行的替代方案:换用可用的天气API

既然雅虎的API已经凉了,你得换个能用的,比如OpenWeatherMap、WeatherAPI这些。这里给你举个OpenWeatherMap的例子(需要先去官网免费申请一个API密钥):

const API_KEY = '你的免费API密钥';
const CITY = 'Auckland';

// 调用OpenWeatherMap的当前天气接口
fetch(`https://api.openweathermap.org/data/2.5/weather?q=${CITY}&appid=${API_KEY}&units=imperial`)
  .then(res => res.json())
  .then(data => {
    const temp = data.main.temp; // 华氏度,换成units=metric就是摄氏度
    const iconCode = data.weather[0].icon;
    const iconUrl = `http://openweathermap.org/img/wn/${iconCode}@2x.png`; // 直接拿到图标链接

    console.log(`奥克兰当前温度:${temp}°F`);
    console.log(`天气图标:${iconUrl}`);
  })
  .catch(err => console.error('请求出错:', err));
最后再总结下你的问题
  1. 最根本的问题是雅虎天气API已经停止服务,返回的不是预期的天气数据,导致你代码里要访问的数组/属性全是undefined,调用map时触发错误;
  2. 其次,代码里缺少必要的空值检查,就算API正常,一旦返回结构变化,也容易踩同样的坑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:13:29