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

如何在React应用中将API获取的数据加载到Gridjs中

React中API数据适配Gridjs展示方案

我正在React应用里尝试把API查询结果展示到Gridjs表格中,需要处理OpenAPI生成的路由响应格式。

可正常运行的基础代码

function App() {
  const [items, setItems] = useState<any[]>([]);
  const getTheItems = async (filters: string,includeItemTypes:string, limit:number,recursive:boolean) => {
    try {
      const fetchedItems = await itemsServiceApi.getItems(filters, includeItemTypes, limit, recursive);
      const obj = JSON.parse(JSON.stringify(fetchedItems.data));
      console.log(obj.Items);
      setItems(obj.Items);
    } catch (error) {
      console.warn(error)
    }
  };

  useEffect(() => {
    getTheItems("IsNotFolder","Movies",20,true);
  }, []);

  return (
    <div className="App">
    <header className="App-header">
      <img src={logo} className="App-logo" alt="logo" />
      {items.map((item, index) => (
      <div key={index} id={item.Id}> {item.Name} <br />
      </div>
      ))}
    </header>
  </div>
  );
};
export default App;

目标实现代码(使用Gridjs展示)

function App() {
  const [items, setItems] = useState<any[]>([]);
  const getTheItems = async (filters: string,includeItemTypes:string, limit:number,recursive:boolean) => {
    try {
      const fetchedItems = await itemsServiceApi.getItems(filters, includeItemTypes, limit, recursive);
      const obj = JSON.parse(JSON.stringify(fetchedItems.data));
      console.log(obj.Items);
      setItems(obj.Items);
    } catch (error) {
      console.warn(error)
    }
  };

  useEffect(() => {
    getTheItems("IsNotFolder","Movies",20,true);
  }, []);

  return (
    <div>
      <Grid
        data={items}
        columns={['Name', 'Id']}
        pagination={{
          limit: 5,
        }}
      />
    </div>
  );
};
export default App;

当前API返回的items数组结构

[
    {
        "Name": "The Shepherd",
        "ServerId": "3ac3356dc26a430eabc7ab193ad16189",
        "Id": "10092347",
        "ChannelId": "9476798",
        "RunTimeTicks": 72000000000,
        "Type": "Program",
        "ImageTags": {
            "Primary": "77c5cf117131ead7a9e31012ce673d0c"
        },
        "BackdropImageTags": [],
        "MediaType": "Video",
        "StartDate": "0001-01-01T00:00:00.0000000Z"
    },
    {
        "Name": "Olympia",
        "ServerId": "3ac3356dc26a430eabc7ab193ad16189",
        "Id": "10100423",
        "ChannelId": "9476793",
        "RunTimeTicks": 36000000000,
        "Type": "Program",
        "ImageTags": {
            "Primary": "3e59d6854f930ea9bb21b2046e46426f"
        },
        "BackdropImageTags": [],
        "MediaType": "Video",
        "StartDate": "0001-01-01T00:00:00.0000000Z"
    }
]

解决方案

1. 简化数据处理逻辑

JSON.parse(JSON.stringify(fetchedItems.data))属于冗余操作,OpenAPI生成的客户端返回的data本身就是可直接使用的JSON对象,直接提取Items字段即可:

const fetchedItems = await itemsServiceApi.getItems(filters, includeItemTypes, limit, recursive);
setItems(fetchedItems.data.Items);

2. 确保Gridjs正确匹配数据

Gridjs支持直接传入对象数组,但为了避免字段名大小写、嵌套结构等潜在问题,建议显式指定列的accessor:

<Grid
  data={items}
  columns={[
    { name: '名称', accessor: (item) => item.Name },
    { name: 'ID', accessor: (item) => item.Id }
  ]}
  pagination={{
    limit: 5,
  }}
/>

3. 添加加载状态优化体验

初始数据未加载完成时,可显示加载提示避免空表格:

return (
  <div>
    {items.length === 0 ? (
      <div>加载中...</div>
    ) : (
      <Grid
        data={items}
        columns={[
          { name: 'Name', accessor: 'Name' },
          { name: 'Id', accessor: 'Id' }
        ]}
        pagination={{ limit: 5 }}
      />
    )}
  </div>
);

4. 类型定义优化(可选)

为了TypeScript类型安全,建议定义Item接口:

interface Item {
  Name: string;
  Id: string;
  ServerId: string;
  // 其他字段按需补充
}

const [items, setItems] = useState<Item[]>([]);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 18:37:00