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

React Native遍历JSON响应报错:TypeError: responseData.map is not a function

解决React Native中fetch响应调用map时报错TypeError的问题

你遇到的TypeError: responseData.map is not a function问题很典型——你把map()用在了错误的数据类型上。咱们先看你的JSON响应结构:整个返回的responseData是一个包含多个键的对象,只有user和products这两个字段的值才是数组,而map()是数组专属的方法,直接在整个对象上调用它肯定会报错。

给你整理了正确的处理方式,分步骤来:

第一步:确保正确解析JSON响应

首先要确认你已经把fetch的响应正确转换成了JSON对象,基础代码是这样的:

fetch('你的接口URL')
  .then(response => response.json())
  .then(responseData => {
    // 在这里处理你的数据
  })
  .catch(err => console.error('请求出错:', err));

第二步:遍历user数组打印id

针对user数组,你需要单独取出这个字段再调用map():

// 遍历user数组,打印每个user的id
responseData.user.map(user => {
  console.log(user.id);
});

第三步:遍历products数组打印name

同样的,处理products数组也要单独操作:

// 遍历products数组,打印每个product的name
responseData.products.map(product => {
  console.log(product.name);
});

额外的安全处理(可选)

如果接口可能返回user或products为非数组(比如null、undefined),可以加个类型判断避免报错:

// 安全遍历user数组
if (Array.isArray(responseData.user)) {
  responseData.user.map(user => console.log(user.id));
}

// 安全遍历products数组
if (Array.isArray(responseData.products)) {
  responseData.products.map(product => console.log(product.name));
}

这样修改后,就能正常打印你需要的user.id和product.name了~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 06:51:14