React和Axios的新手,试图找出如何让它发挥作用。
所以从我参加的React课程中,我了解到我应该将服务器调用放在componentDidMount
中,所以我的代码看起来像这样:
state = {
values : {}
}
componentDidMount () {
axios.get(query_url, {headers:headers}).then(response => {
//console.log(response.data.data[0]);
for (let i=0; i<response.data.data.length; i++) {
console.log(response.data.data[i]);
let data_url = some_url + response.data.data[i];
axios.get(data_url, {headers:headers}).then(response => {
for (let j=0; j<response.data.data[0]['metrics'].slice(0, 30).length; j++) {
let detail = response.data.data[0]['metrics'][j];
if (detail['country'] === 'US') {
usaVal += detail['value'];
} else {
worldVal += detail['value'];
}
this.setState({values: {usa: usaVal, world: worldVal}});
}
}
}
})
我们假设所有some_url
,headers
,query_url
都已正确设置(我注释掉的行)。
我的目标是获得最终的usaVal
和worldVal
,但随着数据的获取,状态会更新。我如何确保获得最终号码?
async componentDidMount () {
const url = "some url";
const queryUrl = url + "some other crap";
const headers = {"auth": "some auth"};
//first level: get query params
const response = axios.get(queryUrl, {headers: headers});
if (response) {
response.then(response => {
const data = await Promise.all(response.map((data, index) => axios.get(`${url}${data}`, {headers: headers})));
console.log(data);
})
}
现在我得到了Syntax error: await is a reserved word
从Error using async/await in React Native开始,我需要async
与await
一起使用。我没有正确使用它吗?
答案 0 :(得分:1)
您可以async-await
Promise.all
async componentDidMount () {
const response = await axios.get(query_url, {headers:headers})
//console.log(response.data.data[0]);
if(response) {
const data = await Promise.all(response.data.data
.map((data, index) => axios.get(`${some_url}${data}`, {headers:headers})
))
// handle responses
let usaVal = 0, worldVal = 0;
data.forEach(response => {
for (let j=0; j<response.data.data[0]['metrics'].slice(0, 30).length; j++) {
let detail = response.data.data[0]['metrics'][j];
if (detail['country'] === 'US') {
usaVal += detail['value'];
} else {
worldVal += detail['value'];
}
}
})
this.setState({values: {usa: usaVal, world: worldVal}});
}
}