React.js使用Axios调用接口时报profile.map is not a function错误
问题修复方案
核心错误原因
https://randomuser.me/api/?results=50接口返回的响应根结构是对象,不是数组,你直接将整个响应对象赋值给初始为数组的profile状态,导致profile从数组变为对象,自然不具备map方法。
需修改的点:
- 赋值状态时取响应对象的
results字段,该字段才是50条用户数据组成的数组 - 给
useEffect添加空依赖数组,避免组件挂载后无限重复发起接口请求 - 修正
map的参数使用逻辑:map回调第一个参数是当前遍历的数组项,第二个是索引,无需再通过索引从原数组取值 - 新增数组非空判断,避免异常场景下调用
map报错
修复后的list.jsx完整代码
import { useState, useEffect } from "react"; import axios from "axios"; import "./list.css"; const List = () => { const [profile, setData] = useState([]); useEffect(() => { axios.get("https://randomuser.me/api/?results=50").then( res => { console.log(res.data); // 取results字段赋值,该字段才是用户数组 setData(res.data.results); } ) }, []); // 加空依赖数组,仅挂载时请求一次 return ( <div className="main"> {/* 加非空判断,避免异常 */} {profile?.map((user, index) => <div className="listCard" key={index}> <div className="userName"> <div style={{ margin: "10px 0 10px 20px" }}>Username : {user.login.username}</div> </div> <div className="details"> <div className="topDetails"> <div className="nameAndEmail"> {/* 替换硬编码内容为动态数据 */} <div style={{ fontSize: "25px", fontWeight: "bold" }}>{user.name.title} {user.name.first} {user.name.last}</div> <div style={{ fontSize: "20px", color: "rgb(128, 128, 112)", marginTop: "20px" }}>Email: {user.email}</div> </div> <div className="picture"> <div className="imageBox"> <img src={user.picture.large} alt="用户头像"/> </div> </div> </div> <div className="bottomDetails"> <div className="nationality"> <div style={{ fontWeight: "bold", fontSize: "22px" }}>User for {new Date().getFullYear() - new Date(user.registered.date).getFullYear()} years</div> <div style={{ fontSize: "20px", marginBottom: "8px" }}>Age: {user.dob.age}</div> <div style={{ fontSize: "20px", marginBottom: "8px" }}>Nationality: {user.nat}</div> <div style={{ fontSize: "18px", marginBottom: "8px" }}>#: {user.cell}</div> </div> <div className="address"> <div style={{ textAlign: "center", fontSize: "18px", fontWeight: "bold" }}>Address:</div> <div>{user.location.street.number} {user.location.street.name},</div> <div>{user.location.city}, {user.location.state}, {user.location.country}</div> <div>{user.location.postcode}</div> </div> </div> </div> </div> )}; </div> ); } export default List;
内容的提问来源于stack exchange,提问作者coolhack7
相关产品推荐
相关产品推荐

