React渲染表格时遇Uncaught TypeError: employees.map错误求助
问题:React渲染表格时出现
Uncaught TypeError: employees.map is not a function错误 Uncaught TypeError: employees.map is not a function
我是React和Node.js初学者,从后端获取数据渲染到表格时碰到上述错误。Postman测试后端接口正常,但React端连接时出问题。以下是相关代码、控制台输出和Postman返回结果:
组件代码
import axios from 'axios'; import { useEffect, useState } from "react"; function CustomerCrud() { const [_id, setId] = useState(''); const [name, setName] = useState(""); const [address, setAddress] = useState(""); const [phone, setMobile] = useState(""); const [employees, setUsers] = useState([]); useEffect(() => { (async () => await Load())(); }, []); async function Load() { const result = await axios.get("http://localhost:8000/user/getAll"); setUsers(result.data); console.log(result.data); } return ( <div> <table class="table table-dark" align="center"> <thead> <tr> <th scope="col">Employee Id</th> <th scope="col">Employee Name</th> <th scope="col">Employee Address</th> <th scope="col">Employee Mobile</th> <th scope="col">Option</th> </tr> </thead> {employees.map(function fn(employee) { return ( <tbody> <tr> <th scope="row">{employee._id} </th> <td>{employee.name}</td> <td>{employee.address}</td> <td>{employee.phone}</td> <td> <button type="button" class="btn btn-warning" onClick={() => editEmployee(employee)} >Edit</button> <button type="button" class="btn btn-danger" onClick={() => DeleteEmployee(employee._id)}>Delete</button> </td> </tr> </tbody> ); })} </table> </div> ); }
控制台输出
Object data: Array(1) 0: address: "indiafabiiii" name: "kobi" phone: "53423332" __v: 0 _id: "63a3d39df8a99b15db6eb9f6" [[Prototype]]: Object length: 1 [[Prototype]]: Array(0) status: true
Postman返回结果
{ "status": true, "data": [ { "_id": "63a3d39df8a99b15db6eb9f6", "name": "kobi", "address": "indiafabiiii", "phone": "53423332", "__v": 0 } ] }
解决方法
修正数据赋值逻辑
后端返回的是包含status和data数组的对象,你当前把整个对象赋值给了employees状态,导致employees是对象而非数组,无法调用map方法。修改Load函数的赋值代码:async function Load() { const result = await axios.get("http://localhost:8000/user/getAll"); // 提取返回对象中的data数组赋值给employees setUsers(result.data.data); console.log(result.data.data); }优化HTML结构与React规范
当前代码将<tbody>放在map循环内,会生成多个独立的<tbody>标签,不符合HTML表格规范。同时React列表渲染需要给子元素添加唯一key属性:<table class="table table-dark" align="center"> <thead> <tr> <th scope="col">Employee Id</th> <th scope="col">Employee Name</th> <th scope="col">Employee Address</th> <th scope="col">Employee Mobile</th> <th scope="col">Option</th> </tr> </thead> <tbody> {employees.map(function fn(employee) { return ( <tr key={employee._id}> <th scope="row">{employee._id} </th> <td>{employee.name}</td> <td>{employee.address}</td> <td>{employee.phone}</td> <td> <button type="button" class="btn btn-warning" onClick={() => editEmployee(employee)} >Edit</button> <button type="button" class="btn btn-danger" onClick={() => DeleteEmployee(employee._id)}>Delete</button> </td> </tr> ); })} </tbody> </table>
内容的提问来源于stack exchange,提问作者abi jega
相关产品推荐
相关产品推荐

