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

React中嵌套API调用填充表格的实现方案问询

在React中实现带嵌套API调用的表格

我来给你捋捋怎么实现这个需求,核心就是先拿经销商的车型列表,再逐个车型拉取对应的感兴趣客户,最后把数据整合到表格里展示。咱们一步步来:

1. 基础实现思路

  • 第一步:调用/inventory/:idOfDealership/cars获取经销商的新车列表
  • 第二步:对每个车型,调用对应的客户API(假设是/cars/${idOfCar}/interested-customers)获取客户列表
  • 第三步:处理客户数量的显示逻辑,比如1个客户直接显示名字,多个客户显示「XX和另外N人」
  • 第四步:把数据渲染成两列的表格

2. 具体代码实现

这里用React函数组件来写,搭配useState和useEffect管理状态和副作用:

import { useState, useEffect } from 'react';

const CarCustomerTable = ({ idOfDealership }) => {
  const [carsWithCustomers, setCarsWithCustomers] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      setIsLoading(true);
      setError(null);
      try {
        // 第一步:获取经销商的车型列表
        const carsRes = await fetch(`/inventory/${idOfDealership}/cars`);
        if (!carsRes.ok) throw new Error('Failed to fetch cars');
        const cars = await carsRes.json();

        // 第二步:批量获取每个车型的客户列表
        const carsWithCustomersPromises = cars.map(async (car) => {
          const customersRes = await fetch(`/cars/${car.idOfCar}/interested-customers`);
          if (!customersRes.ok) throw new Error(`Failed to fetch customers for ${car.name}`);
          const customers = await customersRes.json();
          return { ...car, customers };
        });

        // 等待所有请求完成
        const result = await Promise.all(carsWithCustomersPromises);
        setCarsWithCustomers(result);
      } catch (err) {
        setError(err.message);
      } finally {
        setIsLoading(false);
      }
    };

    fetchData();
  }, [idOfDealership]);

  // 处理客户显示文本的辅助函数
  const getCustomerDisplayText = (customers) => {
    if (customers.length === 0) return '无感兴趣客户';
    if (customers.length === 1) return customers[0].name;
    return `${customers[0].name}和另外${customers.length - 1}人`;
  };

  if (isLoading) return <div>加载中...</div>;
  if (error) return <div>出错了:{error}</div>;

  return (
    <table border="1" style={{ width: '100%', borderCollapse: 'collapse' }}>
      <thead>
        <tr>
          <th>车型名称</th>
          <th>感兴趣的客户</th>
        </tr>
      </thead>
      <tbody>
        {carsWithCustomers.map((car) => (
          <tr key={car.idOfCar}>
            <td>{car.name}</td>
            <td>{getCustomerDisplayText(car.customers)}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
};

export default CarCustomerTable;

3. 关键细节优化

  • 请求性能优化:如果经销商的车型很多,直接用Promise.all会发起大量并行请求,可能触发后端限流。你可以用分批请求(比如每次发5个),或者引入React Query/SWR这类数据管理库,它们自带缓存、请求重试和并发控制的能力。
  • 错误处理:上面的代码已经做了基础的错误捕获,你还可以给每个车型的请求单独处理错误,比如某个车型的客户数据拉取失败时,显示「获取客户数据失败」而不是整个表格崩溃。
  • 加载状态细化:如果想要更友好的加载体验,可以给每一行单独显示加载状态,而不是整个表格显示加载中。
  • 数据缓存:如果用户频繁切换经销商,缓存已请求过的车型和客户数据能提升体验,React Query/SWR这类库能帮你轻松实现。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:22:33