gpt4 book ai didi

javascript - React Axios API 调用与数组循环给出错误的顺序?

转载 作者:行者123 更新时间:2023-12-03 02:36:45 25 4
gpt4 key购买 nike

我正在学习 React 并使用数组进行一些 axios api 调用。我做了一个通过coinmarketcap api收集数据的代码来学习。

所以,我的目的是使用硬编码的加密货币 id 数组从 api 获取价格,并将它们推送到价格数组中。但我遇到了价格数组的问题,因为价格都困惑了。我应该按这个顺序得到一个数组

[比特币价格、以太坊价格、stellarprice、rippleprice]

但是当我在浏览器中运行它时,价格是随机出现的,而不是按这个顺序,有时我得到了我的订单,有时却没有。我使用了一个按钮,onClick 调用了 getPrice 方法。有谁知道我的代码出了什么问题?谢谢!

constructor(){
super();

this.state = {
cryptos:["bitcoin","ethereum","stellar","ripple"],
prices:[]
};

this.getPrice = this.getPrice.bind(this);

}


getPrice(){
const cryptos = this.state.cryptos;
console.log(cryptos);

for (var i = 0; i < cryptos.length; i++){
const cryptoUrl = 'https://api.coinmarketcap.com/v1/ticker/' + cryptos[i];

axios.get(cryptoUrl)
.then((response) => {
const data = response.data[0];
console.log(data.price_usd);

this.state.prices.push(data.price_usd);
console.log(this.state.prices);
})

.catch((error) => {
console.log(error);
});
}

}

最佳答案

如果你想按照异步调用的顺序接收数据,可以使用 Promise.all ,等待数组的所有 Promise 都被执行并解决,并按照执行顺序返回值。

const cryptos = ['bitcoin', 'ethereum', 'stellar', 'ripple'];
const arr = [];
for (var i = 0; i < cryptos.length; i++){
const cryptoUrl = 'https://api.coinmarketcap.com/v1/ticker/' + cryptos[i];
arr.push(axios.get(cryptoUrl));
}

Promise.all(arr).then((response) =>
response.map(res => console.log(res.data[0].name, res.data[0].price_usd))
).catch((err) => console.log(err));

关于javascript - React Axios API 调用与数组循环给出错误的顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48511975/

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