React中axios.get请求时报this.state.persons.map不是函数报错
报错根因
TypeError: this.state.persons.map is not a function的触发逻辑非常直接:
- 你在
componentDidMount里执行了this.setState({persons:res.data}),而res.data是包含results、info两个顶级字段的普通对象,不是数组。此时原本为空数组的persons状态被替换成了对象,对象不存在map方法,自然触发类型错误。 - 后续即使修正了赋值逻辑,每个用户节点下的
name字段是包含title/first/last的嵌套对象,不是可直接渲染的字符串,直接输出会生成[object Object]的无效内容。
修复方案
- 调整接口赋值逻辑:从响应数据中提取真正的用户数组,也就是从
res.data中取results字段赋值给persons状态。 - 修正姓名取值逻辑:从嵌套的
name对象中拼接完整姓名字符串用于渲染。 - 增加兜底判断:遍历前校验
persons是否为可遍历的数组,避免接口异常、数据结构不符合预期时再次触发类型报错。
修正后完整代码
import React, { Component } from 'react' import './form.css' import axios from 'axios' class form extends Component{ constructor(props){ super(props); this.state={ answer:'', persons:[] } this.handleChange=this.handleChange.bind(this); this.handleSubmit=this.handleSubmit.bind(this); } componentDidMount(){ axios.get('https://api.randomuser.me') .then(res=>{ // 从返回结构中提取真正的用户数组赋值给persons this.setState({persons: res.data.results}); }) } handleSubmit=(e)=>{ } handleChange=(e)=>{ this.setState({ answer:e.target.value, }) } render(){ return ( <div> <section className="login"> <div className="loginContainer"> <div className="heading"> </div> <div className="data-wrapper"> {/* 增加数组校验兜底,同时拼接嵌套结构里的姓名字段 */} {Array.isArray(this.state.persons) && this.state.persons.map(person => ( <h2 key={person.login.uuid}>{`${person.name.title} ${person.name.first} ${person.name.last}`}</h2> ))} </div> </div> </section> </div> ) } } export default form
补充提示:React 渲染列表时必须为每个节点提供唯一的
key属性,这里使用接口返回的每个用户自带的login.uuid作为key值,可消除列表渲染的控制台警告。
内容的提问来源于stack exchange,提问作者tanmya
相关产品推荐
相关产品推荐

