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

MUI X Data Grid展示Airtable数据仅显示表头无行数据问题求解

问题根因

Airtable接口返回的records数组中的每条数据是封装后的实例对象,业务字段全部存放在fields属性下,而MUI X Data Grid要求传入的rows数组的每一项是平面对象,字段和你定义的columns中的field属性一一对应,直接传原records数组组件无法识别到对应字段,就会出现只有列头没有数据的情况。

修复方案

在给rows赋值前对原records数组做一层格式转换,把id和fields下的业务字段平铺为单个对象即可。如果不需要分批拉取大量数据,可以直接用Airtable的all方法一次性获取全量数据,修改后的代码如下:

import React, { useEffect, useState } from "react";
import { makeStyles } from "@material-ui/styles";
import { Container } from "@material-ui/core";
import { DataGrid } from "@mui/x-data-grid";
import Airtable from "airtable";
const base = new Airtable({ apiKey: "*****" }).base(
  "*****"
);

const useStyles = makeStyles(
  (theme) => ({
    container: {
      marginTop: "10vh",
    },
  }),
  {}
);
const col = [
  { field: "id", headerName: "ID", width: 90 },
  { field: "name", headerName: "Institution Name", width: 150 },
  { field: "town", headerName: "Location Town", width: 150 },
  { field: "state", headerName: "State", width: 150 },
];
export default function CE3() {
  const classes = useStyles();
  const [rows, setRows] = useState([]);

  useEffect(() => {
    base("Table 1")
      .select({
        maxRecords: 3,
        view: "Grid view",
      })
      .all()
      .then(records => {
        // 转换数据格式适配DataGrid要求
        const formattedRows = records.map(record => ({
          id: record.id,
          ...record.fields
        }))
        setRows(formattedRows)
      })
  }, []);

  return (
    <div>
      <Container fixed={true} className={classes.container}>
        Select at least <strong>1</strong> college
        <br />
        <DataGrid
          rows={rows}
          columns={col}
          pageSize={5}
          rowsPerPageOptions={[5]}
          checkboxSelection
          disableSelectionOnClick
        />
      </Container>
    </div>
  );
}

如果你确实需要用eachPage分批拉取大量数据,修改赋值逻辑为追加数据即可:

.eachPage((records, fetchNextPage) => {
  const formattedPage = records.map(r => ({id: r.id, ...r.fields}))
  setRows(prevRows => [...prevRows, ...formattedPage])
  fetchNextPage()
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 22:48:03