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

React(TypeScript)遍历API返回数据报错:map不是函数

解决TypeError: data.map is not a function问题,提取组件名称数组

问题背景

API返回的数据结构如下:

{
    "projectId": 203,
    "components": [
        {
            "id": 10310,
            "name": "Play Challenges",
            "quantity": 24.07
        },
        {
            "id": 10301,
            "name": "My Creation",
            "quantity": 12.96
        }
    ]
}

你尝试用以下代码提取所有组件的name属性生成string[]:

const content: string[] = data.map((components : any ) => {
    return components.name
});

但触发错误:

Uncaught TypeError: data.map is not a function

问题原因

map是数组的专属方法,而你直接调用的data是一个顶层对象(包含projectId和components两个属性),并非数组,所以无法调用map。真正的目标数组是data.components。

解决方案

直接对data.components数组调用map即可,同时建议添加类型定义替代any,提升代码健壮性:

基础实现

// 访问data中的components数组,再提取name属性
const content: string[] = data.components.map(component => component.name);

严谨实现(含类型定义与空值保护)

// 定义接口规范数据结构
interface Component {
    id: number;
    name: string;
    quantity: number;
}

interface ApiResponse {
    projectId: number;
    components: Component[];
}

// 假设data已通过API请求获取并断言为ApiResponse类型
const data: ApiResponse = await fetch('/your-api-url').then(res => res.json());

// 空值保护:避免components不存在时报错
const content: string[] = (data.components || []).map(component => component.name);

这样就能正确生成包含所有组件名称的字符串数组,同时避免类型错误和空值异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 15:58:16