gpt4 book ai didi

javascript - 在ReactJS中超过api限制时的错误处理

转载 作者:行者123 更新时间:2023-12-03 09:07:24 27 4
gpt4 key购买 nike

我是ReactJs的新手,这是从truepush api获取数据的代码。

export const getAllCampaign = () => {
return fetch(`https://api.truepush.com/api/v1/listCampaign/1`, {
method: "GET",
headers: {
Authorization: `${TOKEN}`,
"Content-Type": "application/json",
},
})
.then(response => {
return response.json()
})
.catch(err => console.log(err))
}
此api有限制,一旦超过限制,它就会在此处显示“campaigns.map not a function”错误:
    const allData = campaigns.map((campaign, i) => ({
...campaign,
...stats[i].data
}));
这是我的完整代码:
import React, {useState, useEffect} from 'react';
import {getAllCampaign, loadStats} from "../helpers/coreapihelpers";

const TableRow = () => {

const [campaigns, setCampaigns] = useState([]);
const [stats, setStats] = useState([]);

const loadAllCampaigns = () => {
getAllCampaign()
.then(data => { setCampaigns(data.data) })
.catch(err => { console.log(err) });
};

const loadAllStats = () => {
loadStats()
.then(data => { setStats(data) })
.catch(err => { console.log(err) });
}

useEffect(() => {
loadAllCampaigns();
loadAllStats();
}, [])

const allData = campaigns.map((campaign, i) => ({
...campaign,
...stats[i].data
}));

console.log(allData);

return (
<div className="container">
<div className="row">
<div className="col-xs-12">
<div className="table-responsive" data-pattern="priority-columns">
<table className="table table-bordered table-hover">
<thead>
<tr>
<th>Sr. No</th>
<th>Campaign Id</th>
<th>Campaign Name</th>
<th>Campaign Status</th>
<th>Reach</th>
<th>Sent</th>
<th>Delivered</th>
<th>Views</th>
<th>Clicks</th>
<th>Unsubscribers</th>
</tr>
</thead>
<tbody>
{allData.map(
(
{
campaignId,
campaignTitle,
campaignStatus,
Reach,
Sent,
Delivered,
Views,
Clicks,
Unsubscribers
},
index
) => (
<tr key={index}>
<td>{index + 1}</td>
<td>{campaignId}</td>
<td>{campaignTitle}</td>
<td>{campaignStatus}</td>
<td>{Reach}</td>
<td>{Sent}</td>
<td>{Delivered}</td>
<td>{Views}</td>
<td>{Clicks}</td>
<td>{Unsubscribers}</td>
</tr>
)
)}
</tbody>
</table>
</div>
</div>
</div>
</div>
);
}

export default TableRow;

我如何显示一个简单的h1标签,说明api限制超出或无法获取数据时,限制超过了?

最佳答案

campaigns.map not a function基本上是此错误,这意味着您的广告系列没有保存任何要映射的数据或数组数据。您可以通过调试和调试来检查它。
由于api给出了error,因此您可以采用错误状态,并在解决Promise时检查响应是否成功,如果不成功,则将error设置为true,然后在广告系列中将其设置为[],因此,请使用链式的?.检查广告 Activity 是否为null的属性,然后搜索其关键字

  const allData = campaigns?.map((campaign, i) => ({
...campaign,
...stats[i].data
}));
并在组件中放入条件语句作为返回:
    return allData ?
<div className="container">
<div className="row">....
:<div>ERROR</div>

关于javascript - 在ReactJS中超过api限制时的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65842467/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com