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

Material UI DataGrid迭代渲染用户列表时的空白与报错问题解决

MUI DataGrid 用户信息表格展示问题修复指南

现有代码核心问题

  • 数据映射逻辑错误:当前rows数组直接读取userLists的顶层属性,但userLists本身是存储全量用户的数组,直接取userID、userFirstName这类属性会拿到undefined,无法生成合法的行数据
  • 渲染逻辑错位:在userLists.map循环内部反复渲染DataGrid组件,既没有正确解构循环遍历的单个用户对象,还会根据用户列表长度生成N个独立的表格实例,直接触发组件渲染异常
  • 不必要的重复渲染:无动态变化的列定义数组columns如果每次组件渲染都重新创建,会造成不必要的性能损耗,这类固定配置可以移到组件外部定义
  • 缺少空值兜底:如果userLists是异步获取的数据,初始值为undefined时直接读取属性或遍历会直接抛出异常

修复后的参考实现

// 固定列定义移到组件外部,避免每次渲染重复生成配置
const columns = [
  { field: 'id', headerName: 'ID', width: 70 },
  { field: 'firstname', headerName: 'First name', width: 130 },
  { field: 'lastName', headerName: 'Last name', width: 130 },
  { field: 'userName', headerName: 'Username', width: 130 },
  { field: 'userEmail', headerName: 'Email', width: 180 },
  { field: 'userRole', headerName: 'Role', width: 80 }
];

// 组件内接收用户列表参数,加默认空数组做兜底
function UserInfoTable({ userLists = [] }) {
  // 遍历全量用户列表,映射成与列定义字段匹配的行数据
  const rows = userLists.map(user => ({
    id: user.userID,
    firstname: user.userFirstName,
    lastName: user.userSurname,
    userName: user.username,
    userEmail: user.userEmail,
    userRole: user.userRoleID
  }));

  return (
    <div style={{ height: 400, width: '100%' }}>
      {/* 仅渲染一次DataGrid,直接传入映射完成的全量行数据 */}
      <DataGrid
        rows={rows}
        columns={columns}
        pageSize={Math.max(rows.length, 10)} // 根据行数据总量调整分页大小,实现全量展示
        checkboxSelection
      />
    </div>
  );
}

效果校验要点

  • 确认列定义的field值与行数据的键名完全匹配,大小写不一致会导致对应列展示空白
  • 若需要一次性展示全部用户信息,将pageSize设置为大于等于用户总数量的值即可,无需自行循环渲染表格
  • 给异步加载的用户列表添加初始空值兜底,避免数据未返回时触发空指针类报错

内容的提问来源于stack exchange,提问作者James Gee

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.24 13:06:04