与Axios反应,对于我从GET获得的响应,我想使用另一个GET,我想总结某些字段的值

时间:2018-04-11 04:49:43

标签: javascript reactjs axios

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_urlheadersquery_url都已正确设置(我注释掉的行)。

我的目标是获得最终的usaValworldVal,但随着数据的获取,状态会更新。我如何确保获得最终号码?

编辑:按照@Shubham Khatri的建议,我的代码现在看起来像

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开始,我需要asyncawait一起使用。我没有正确使用它吗?

1 个答案:

答案 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}});
     }
}