将2个API数据源加入1个反应表的最佳方法?

问题描述

我需要来自2个不同API的数据,均支持分页

如何以高效的方式在表中显示联接的数据?

我需要加入他们的id,但是一个API返回的数据少于另一个,因此我不能简单地将1与1匹配。我需要实现一个过滤器。

将暴力数据源A映射到B的唯一方法

解决方法

如果数据来自两个不同的API,而您要进行单独的请求,则可以有很多选择。我个人的喜好是在控制器中放置state,并在其中map id进行每个响应,然后可以通过id选择其他数据:

import React,{ useState,useEffect } from 'react';
import { keyBy } from 'lodash';

function TableComponent(props) {
  // Destructure your props...I'm assuming you pass some id into fetch data
  const { id } = props;
  
  // State
  const [tableData,setTableData] = useState([]);

  // Load data when id changes
  useEffect(() => {
    fetchData()
  },[id]);

  async function fetchData() {
    // Get your data from each source
    const apiData_A = await fetchDataFromAPI_A(id);
    const apiData_B = await fetchDataFromAPI_B(id);
    // Key each data set by result ids
    const resultsMappedById_A = keyBy(apiData_A,'id');
    const resultsMappedById_B = keyBy(apiData_B,'id');
    // Combine data into a single set
    // this assumes your getting same results from each api
    const combinedDataSet = Object.keys(resultsMappedById_A)
      .reduce((acc,key) => {
        // Destructure results together,merging objects
        acc.push({
          ...resultsMappedById_A[key],...resultsMappedById_B[key]
        });
        return acc;
      },[]);
    setTableData(combinedDataSet);
  }

  async function fetchDataFromAPI_A(id) {
    // Fetch your data and return results
  }

  async function fetchDataFromAPI_A(id) {
    // Fetch your data and return results
  }

  function renderTableRow(data) {
    return (
      <tr>
        <td>{data.id}</td>
        <td>{data.apiAProp}</td>
        <td>{data.apiBProp}</td>
      </tr>
    );
  }


  return (
   <table>
     { tableDataSet.map(renderTableRow) }
   </table>
  );
}

请注意,可能有更有效的方法来执行此操作,具体取决于您如何获取数据以及响应的内容,但此处提供的概念应该可以解决问题,前提是我根据您提供的信息假设正确。