我正在学习react,并使用数组执行api调用。为了学习,我做了一个代码,通过coinmarketcap收集数据。
因此,我的目的是通过硬编码的加密货币ids数组从api中获取价格,并将它们推入价格数组。但我在价格排列上遇到了问题,因为价格都乱七八糟的。我应该按照这个顺序得到一个数组
比特价格,价格
但是当我在浏览器中运行它时,价格是随机的,而不是这个顺序,有时我得到了我的订单,有时它没有。我使用了一个按钮,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);
});
}
}
发布于 2018-01-29 16:19:48
如果您想按照异步调用的顺序接收数据,您可以使用Promise.all,它等待一个数组的所有承诺被执行并被解析,并按照它们的执行顺序返回值。
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));
发布于 2018-01-29 16:31:14
您可以使用for循环中的闭包来捕获i的值,并在数据返回后将其用作索引,而不是使用push:
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];
(function (x) {
axios.get(cryptoUrl)
.then((response) => {
const data = response.data[0];
console.log(data.price_usd);
var newPrices = this.state.prices;
newPrices[x] = data.price_usd;
this.setState({prices: newPrices});
console.log(this.state.prices);
})
.catch((error) => {
console.log(error);
});
})(i);
}
}
https://stackoverflow.com/questions/48511975
复制相似问题