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

React Native网络请求失败及Cannot read property 'map' of undefined问题求助

解决React Native中网络请求失败与map undefined的问题

咱们先拆解你遇到的两个核心问题:Network request failed(网络请求失败)和cannot read property 'map' of undefined(无法读取undefined的map属性),逐个来搞定:

1. 网络请求失败的核心原因:API已废弃

你当前使用的https://restcountries.eu/rest/v3.1/all这个API服务已经停止运营了,这是导致网络请求失败的直接原因。现在需要替换为官方维护的新API地址:https://restcountries.com/v3.1/all

2. 解决"cannot read property 'map' of undefined"报错

这个错误是因为请求失败时data会变成undefined,直接调用data.map就会触发报错;另外你代码里在map后面加catch是无效的——map是数组方法,不是Promise,不能用catch捕获错误。咱们调整代码的错误处理逻辑:

修正后的请求代码

React.useEffect(() => {
  // 使用官方维护的新API地址
  fetch("https://restcountries.com/v3.1/all")
    .then(response => {
      // 先校验响应是否成功
      if (!response.ok) {
        throw new Error(`请求失败!状态码:${response.status}`);
      }
      return response.json();
    })
    .then((data) => {
      // 校验数据格式,避免非数组数据导致map报错
      if (!data || !Array.isArray(data)) {
        throw new Error("返回数据格式不符合预期");
      }
      // 适配新API的数据结构(旧API的字段名称已变更)
      let areaData = data.map(item => {
        const alpha2Code = item.cca2;
        // 处理电话区号:新API里的区号结构是idd.root + 后缀
        const callingCode = item.idd ? `${item.idd.root}${item.idd.suffixes?.[0] || ''}` : '';
        return {
          code: alpha2Code,
          name: item.name.common, // 新API的国家名称字段为name.common
          callingCode: callingCode,
          flag: `https://countryflagsapi.com/png/${alpha2Code.toLowerCase()}` // 国旗API需要小写代码
        }
      });
      setAreas(areaData);
      // 设置默认选中的美国区域
      if (areaData.length > 0) {
        let defaultData = areaData.filter(a => a.code === "US");
        if (defaultData.length > 0) {
          setSelectedArea(defaultData[0]);
        }
      }
    })
    .catch(err => {
      console.error("请求或数据处理出错:", err);
      // 请求失败时设置默认数据,避免UI崩溃
      const defaultArea = {code: "US", name: "United States", callingCode: "+1", flag: "https://countryflagsapi.com/png/us"};
      setAreas([defaultArea]);
      setSelectedArea(defaultArea);
    });
}, [])

3. 额外的UI容错优化

因为selectedArea初始值是null,虽然请求成功后会赋值,但最好在渲染层再加一层稳妥判断,避免可能的渲染报错:

// 替换原国旗和电话区号的渲染代码
<View style={{ justifyContent: "center", marginLeft: 7 }}>
  <Image 
    source={selectedArea?.flag ? { uri: selectedArea.flag } : images.defaultFlag} // 可准备一张默认国旗图备用
    resizeMode="contain" 
    style={{ width: 30, height: 30 }} 
  />
</View>
<View style={{ justifyContent: "center", marginLeft: 7 }}>
  <Text style={{ color: COLORS.white, ...FONTS.body3 }}>{selectedArea?.callingCode || "+1"}</Text>
</View>

关键修复总结

  • 替换了废弃的API地址为当前可用的官方地址
  • 完善了全链路错误处理,请求失败/数据异常时设置默认值,避免map报错
  • 适配了新API的数据字段结构(旧API的字段名称已变更)
  • 优化了UI层的空值判断,防止渲染崩溃

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 15:08:14