【发布时间】:2020-04-15 15:29:28
【问题描述】:
我正在尝试从 RapidAPI 的 API 中获取 COVID-19 的统计数据。我想按日期获取统计信息,将数据插入图表。问题是 API 链接中只能包含日期,如下所示:
https://covid-19-data.p.rapidapi.com/report/totals?date-format=undefined&format=undefined&date=2020-04-15
我所做的是使用 for 循环获取十个日期并使用 Axios 检索每天的数据,如下所示:
const today = new Date();
const dd = String(today.getDate()).padStart(2, '0');
const mm = String(today.getMonth() + 1).padStart(2, '0');
const [labels, setLabels] = useState([])
useEffect(() => {
for(let i=dd-10; i<dd; i++) {
Axios({
method: 'GET',
url: `https://covid-19-data.p.rapidapi.com/report/totals?date-format=undefined&format=undefined&date=2020-${mm}-${i}`,
headers: {
"x-rapidapi-host": "covid-19-data.p.rapidapi.com",
"x-rapidapi-key": "cfb0f14a9fmsh913ae802309e7c9p175585jsn825aebcbd5ac"
}
})
.then(response => {
let temp = [...labels]
temp.push(response.data[0].date)
setLabels(temp)
})
.catch(error => {
console.log(error)
})
}
}, [])
问题在于,每次 Axios 检索新日期时,labels 都会更改,而不是将新日期附加到 labels 数组。
我在网上做了一些研究,人们说数据尚未加载,因此当我设置状态时,它有点设置空的东西之类的东西,但我不太明白他们在说什么。
除此之外,当它检索数据时,它不会按顺序检索它。例如,今天是 4 月 15 日,它应该按如下顺序检索数据:05 06 07 08 09 10 11 12 13 14,但它只是随机跳转。如果我在 .then() 处进行控制台记录,则会出现:
如您所见,它不按顺序排列。
请帮我看看,我已经用谷歌搜索了解决方案,但无济于事。
【问题讨论】:
-
为什么它没有按顺序返回?
-
调用是异步的,所以我们没有任何保证哪个会先完成。使用
Promise.all,该函数仅在所有函数完成后才解析。现在我们确定结果在那里,我们可以按正确的顺序返回它们。 -
好的,我试试,谢谢
标签: javascript reactjs api axios