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

React Native中map函数报错:undefined is not a function问题求助

解决React Native中的TypeError: undefined is not a function (near '...this.state.categories.map...')问题

嘿,我一眼就看到问题出在哪了!你控制台打印的后端返回数据是个包含数组的对象,但你直接把整个对象塞给了categories,而对象是没有map方法的,这才导致了报错。

先看看你控制台输出的整理后的数据:

{
  "results": [
    {"cate_id": 1, "name": "vehicles"},
    {"cate_id": 2, "name": "home"},
    {"cate_id": 3, "name": "electronics"}
  ],
  "success": true
}

你当前在componentDidMount里是这么赋值的:

this.setState({ categories: res })

这就把categories变成了一个对象,自然没法用数组的map方法。

核心解决方案:修正赋值字段

把上面的代码改成下面这样,直接取返回对象里的results数组:

this.setState({ categories: res.results })

这样this.state.categories就变成了真正的数组,map方法就能正常工作了。

额外优化建议(让代码更健壮)

  • 添加数组校验:在render里先判断categories是不是数组,避免后续数据格式异常时再次报错:
<View > 
  {Array.isArray(this.state.categories) && this.state.categories.map((item ,key)=>( 
    <View key={key}> 
      <Text>{item.name}</Text> 
    </View> 
  ))} 
</View>
  • 修正URL拼写错误:你fetch的地址里写的是cetegories,正确拼写应该是categories,虽然现在后端正常,但这个小错误可能在后续引发问题,建议改掉。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:53:14