如何在ReactJS的同一表格中整合两个不同API的数据?
解决多API数据在表格对应列渲染的问题
问题分析
你当前的问题是把第二个API返回的所有app_name都渲染到了同一个单元格里,原因是addData是一个包含所有名称的数组,直接在<td>中输出数组会把所有元素拼接显示。正确的做法是让每行数据对应第二个API中同位置的app_name。
修改方案
假设两个API返回的数组长度一致,且数据是按顺序一一对应的,直接在遍历data2时通过索引index从app数组中获取对应项的app_name即可,不需要单独创建addData变量:
const App = () => { const [data2, setData2] = useState([]) const [app, setApp] = useState([]) const getData = async () => { try { let url = API1; let url2 = API2; const res = await fetch(url); const dataset = await res.json(); const res2 = await fetch(url2); const dataset2 = await res2.json(); setData2(dataset.data); setApp(dataset2.data) } catch (error) { console.log(error); } }; useEffect(() => { getData() }, []) const DisplayData = data2.map( (item, index) => { // 通过索引获取对应位置的app_name,做空值处理避免报错 const currentAppName = app[index]?.app_name || '暂无数据' return ( <tr key={index}> <td>{index + 1}</td> <td>{new Date(item.date).toDateString()}</td> {/* 这里渲染对应行的app_name */} <td>{currentAppName}</td> <td>{item.requests}</td> <td>{item.responses}</td> <td>{item.impressions}</td> </tr> ) } ) return ( <> <div className="card w-50 mx-auto"> <table className="table table-stripped"> <thead> <tr> <th>S. no</th> <th>Date</th> <th>App</th> <th>Clicks</th> <th>Requests</th> <th>Revenue</th> <th>Fill rate</th> <th>CTR</th> </tr> </thead> <tbody> {DisplayData} </tbody> </table> </div> </> ) }
额外说明
如果两个API的数组长度不一致,或者数据不是按索引对应,你需要先找到两个数据集的关联字段(比如共同的ID),将两个数组合并成一个包含所有所需字段的数组后再进行渲染。例如:
// 假设两个数据有共同的id字段 const mergedData = data2.map(item => { const matchedApp = app.find(appItem => appItem.id === item.id) return { ...item, app_name: matchedApp?.app_name || '暂无数据' } })
之后遍历mergedData来渲染表格即可。
内容的提问来源于stack exchange,提问作者user17043484
相关产品推荐
相关产品推荐

