如何使用React-Native中的fetch在ComponentDidMount中执行多个API调用?

问题描述 投票:1回答:2

在我的componentDidMount函数中,我调用AsyncStorage来获取一些保存的值,然后发出GET请求并获取如下所示的数据:

componentDidMount() {
  AsyncStorage.getItem("token").then(value => {
    const url = 'my url';
    console.log('token:' + value)
    return fetch(url, {
        method: 'GET',
        headers: new Headers({
          'Content-Type': 'application/json',
          'token': 'abcd',
          'jwt': value
        })
      })
      .then((response) => response.json())
      .then((responseJson) => {

        this.setState({
          dataSource: responseJson,
          isLoading: false,
          getValue: value
        })
      })
      .catch((Error) => {
        console.log(Error)
      })
  })
}

现在,我需要再发一个GET请求。假设我想在此函数中再次发出相同的请求,我该怎么做?

javascript react-native
2个回答
1
投票

我从建议的评论中很容易地解决了这个问题。我在两个不同的函数中执行了API调用部分,然后在ComponentDidMount中调用这两个函数,如下面的代码 -

 getFirstApiResposnse() {

  AsyncStorage.getItem("token").then(value => {
    const url = 'my url';
    console.log('token:'+ value)
   return fetch(url, {
    method: 'GET',
    headers: new Headers({
      'Content-Type' : 'application/json',
      'token': 'abcd',
      'jwt': value
    })
  })
   .then((response)=> response.json() )
  .then((responseJson) => {
    this.setState({
      dataSource: responseJson,
      isLoading: false,
      getValue: value

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

  }

  )

};


getSecondApiResponse() {

  AsyncStorage.getItem("token").then(value => {
    const url = 'my url';
    console.log('token:'+ value)
   return fetch(url, {
    method: 'GET',
    headers: new Headers({
      'Content-Type' : 'application/json',
      'token': 'abcd',
      'jwt': value
    })
  })
   .then((response)=> response.json() )
  .then((responseJson) => {
   console.log('####:'+responseJson.cat_note)
    this.setState({

      isLoading: false,
      getValue: value,
    })
  })
  .catch((Error) => {
    console.log(Error)
  });

  }

  )

}

  componentDidMount() {

    this.getFirstApiResponse();
    this.getSecondApiResponse();

  }

0
投票

您也可以使用Promise.all()。这对多个请求很方便。此外,我们可以使用辅助库,如async,并根据项目需要使用forEach,waterFall,series,parallel等方法。这些东西使我们的代码更具可读性和可扩展性

© www.soinside.com 2019 - 2024. All rights reserved.