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

ReactJS:如何等待REST API响应后再加载表格数据

解决Airtable API异步数据加载与Syncfusion React Grid渲染冲突问题

问题根源

  1. 你使用普通数组listOfUsers存储API返回数据,React无法监听普通变量的变更,导致API返回数据后组件不会自动重新渲染。
  2. 组件初始化阶段就渲染Syncfusion Grid,此时listOfUsers为空数组,Grid无法匹配列定义对应的数据字段,触发报错。

修复后的代码

import React, { useState, useEffect } from 'react';
import { GridComponent, Inject, ColumnsDirective, ColumnDirective, Search, Page } from '@syncfusion/ej2-react-grids';

import { employeesGrid } from '../data/dummy';
import { Header } from '../components';

const Users = () => {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const Airtable = require('airtable');
    const base = new Airtable({ apiKey: 'API-KEY' }).base('APP-ID');

    base('Users').select({
      maxRecords: 200,
      view: "Grid view",
      fields: ["Nom complet", "Email"]
    }).firstPage(function (err, records) {
      if (err) { 
        console.error(err); 
        setLoading(false);
        return; 
      }
      const userList = records.map(record => record.fields);
      setUsers(userList);
      setLoading(false);
    });
  }, []);

  const toolbarOptions = ['Search'];
  const editing = { allowDeleting: true, allowEditing: true };

  if (loading) {
    return (
      <div className="m-2 md:m-10 mt-24 p-2 md:p-10 bg-white rounded-3xl">
        <Header category="Page" title="Users" />
        <div className="flex justify-center items-center h-64">
          <p>加载中...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="m-2 md:m-10 mt-24 p-2 md:p-10 bg-white rounded-3xl">
      <Header category="Page" title="Users" />
      <GridComponent
        dataSource={users}
        width="auto"
        allowPaging
        allowSorting
        pageSettings={{ pageCount: 5 }}
        editSettings={editing}
        toolbar={toolbarOptions}
      >
        <ColumnsDirective>
          {/* eslint-disable-next-line react/jsx-props-no-spreading */}
          {employeesGrid.map((item, index) => <ColumnDirective key={index} {...item} />)}
        </ColumnsDirective>
        <Inject services={[Search, Page]} />
      </GridComponent>
    </div>
  );
};

export default Users;

关键修改点说明

  • 使用useState定义users状态变量存储用户数据,loading状态控制加载提示显示
  • 用useEffect钩子在组件挂载后执行Airtable API请求,确保请求只触发一次(依赖项为空数组)
  • API请求完成后通过setUsers更新状态,触发组件重新渲染,Grid会自动加载新数据
  • 添加加载状态判断,在数据未返回时显示加载提示,避免Grid因空数据报错
  • 移除了未使用的employeesData和getRotatedRectangleCoordinates导入,精简代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 12:06:42