如何在React应用中渲染后端返回的响应数据数组?MERN CRUD项目问题
错误点
Array.map()回调参数顺序颠倒:map方法第一个参数为当前遍历的数组元素,第二个为索引,你写的(index,user)会导致无法获取正确的用户对象- map回调未返回JSX节点:你用大括号包裹
<tr>代码但没有添加return关键字,无返回值所以不会渲染内容 - 渲染字段和表头顺序不匹配:表头顺序为No、Name、Email、Phone,原代码字段对应逻辑错误,即使渲染也会出现内容错位
修正后代码
import React, { useEffect, useState } from "react"; import { Link } from "react-router-dom"; import { getUsers } from "./api"; const UserData = () => { const [users, setUser] = useState([]); useEffect(() => { AllUsers(); }, []); const AllUsers = async () => { const response = await getUsers(); console.log(response.data); setUser(response.data); }; return ( <div> <div className="container"> <table className="table table-hover table-bordered mt-3"> <thead> <tr> <th scope="col">No</th> <th scope="col">Name</th> <th scope="col">Email</th> <th scope="col">Phone</th> <th scope="col">Action</th> </tr> </thead> <tbody> {/* 修正参数顺序、返回逻辑、字段匹配 */} {users.map((user, index) => ( <tr key={index}> <th scope="row">{index + 1}</th> <td>{user.name}</td> <td>{user.email}</td> <td>{user.phone}</td> </tr> ))} </tbody> </table> </div> </div> ); }; export default UserData;
如果习惯用显式return写法,也可以把map部分替换为:
{users.map((user, index) => { return ( <tr key={index}> <th scope="row">{index + 1}</th> <td>{user.name}</td> <td>{user.email}</td> <td>{user.phone}</td> </tr> ) })}
内容的提问来源于stack exchange,提问作者Tushar Bhakare
相关产品推荐
相关产品推荐

