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

