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
相关产品推荐
相关产品推荐

