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

调用API获取国家列表时报response.map is not a function类型错误

问题原因

TypeScript类型标注仅做编译时校验,不会约束接口运行时的实际返回值。你调用的接口返回值不是直接的国家数组,而是带countries字段的对象,国家列表实际存在于data.countries属性下。你直接返回整个响应对象,拿到的自然不是数组类型,访问.length、调用.map()都会触发报错。

修复代码

修改getCountries方法,取出响应中实际的数组字段再返回,同时增加数组类型校验兜底:

const getCountries = async (): Promise<CovidInfo[]> => {
    try {
        const response = await fetch("https://covid19.mathdro.id/api/countries");
        const data = await response.json();
        // 从响应对象中取出国家数组,非数组场景兜底返回空数组
        return Array.isArray(data.countries) ? data.countries : [];
    } catch (error) {
        console.log(error);
        return [];
    }
};
注意事项
  • 接口联调阶段建议先打印完整响应体确认字段结构,不要仅凭类型假设返回格式
  • 增加Array.isArray()判断可以避免接口返回结构异常时导致的页面渲染崩溃

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 04:09:16