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

使用Router与useParams调用REST Countries API失败问题排查

问题排查与解决

核心问题1:API返回格式处理错误

REST Countries的/v3.1/alpha/{code}接口返回的是包含单个国家对象的数组,而非单个对象。你直接将整个数组赋值给country状态,后续解构对象属性时自然会得到undefined。

核心问题2(潜在):国家代码大小写问题

你跳转时将cca2转为小写,但官方文档中ISO 3166-1 alpha-2代码是大写格式(如US、CN),虽然接口可能兼容小写,但统一使用大写能避免潜在的匹配问题。


修复步骤

1. 修正API响应处理逻辑

在getCountry函数中,取数组的第一个元素赋值给状态:

const getCountry = async () => {
  try {
    const response = await fetch(
      `https://restcountries.com/v3.1/alpha/${countryName}`
    );
    const data = await response.json();
    // 取数组第一个元素作为单个国家数据
    setCountry(data[0]);
  } catch (error) {
    console.log(error);
  }
};

2. (可选)统一国家代码为大写

修改跳转逻辑,传递大写的cca2:

onClick={() => navigate(`/countrydetail/${cca2.toUpperCase()}`, {})}

3. 添加状态校验避免渲染错误

在渲染组件时,先判断country是否存在,再进行解构:

if (!country) return <div>加载中...</div>;

// 之后再解构渲染
const { name, flags } = country;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 12:30:55