You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中Axios获取数据无法在Table中显示的问题求助

React表格组件渲染问题修复方案

问题排查与修改点:

  • useEffect无限循环:原代码未添加依赖数组,导致组件每次渲染都触发请求,需添加空数组[]限制仅挂载时执行一次。
  • Axios请求写法错误:axios.get无需传入回调函数,接口返回的数据在响应对象的data属性中,需通过response.data获取用户列表。
  • 状态类型不匹配:初始状态user定义为数组,原更新逻辑将其改为对象,应直接把接口返回的数组赋值给状态。
  • 渲染数据层级错误:状态user已是用户数组,无需通过user.data访问;每个循环项本身就是用户对象,直接访问属性即可,无需多余的JSON.stringify和嵌套层级。

修改后的完整代码:

import { useEffect, useState } from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import { Table } from "react-bootstrap";
import axios from "axios";

export default function App() {
  const [users, setUsers] = useState([]); // 变量名改为users更贴合语义

  useEffect(() => {
    axios
      .get("https://jsonplaceholder.typicode.com/users")
      .then((response) => setUsers(response.data))
      .catch((error) => console.error(error));
  }, []); // 添加空依赖数组

  return (
    <div className="App">
      <h3 className="text-primary">User List</h3>
      <Table
        variant="danger"
        striped
        bordered
        hover
        className="shadow-lg text-center"
      >
        <thead>
          <tr>
            <th>id</th>
            <th>Name</th>
            <th>UserName</th>
            <th>Email</th>
          </tr>
        </thead>
        <tbody>
          {users.length > 0 &&
            users.map((user) => (
              <tr key={user.id}>
                <td>{user.id}</td>
                <td>{user.name}</td>
                <td>{user.username}</td>
                <td>{user.email}</td>
              </tr>
            ))}
        </tbody>
      </Table>
    </div>
  );
}

内容的提问来源于stack exchange,提问作者Sougata Mukherjee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 08:56:06