使用React Native获取多个API请求

w9apscun  于 2023-08-07  发布在  React
关注(0)|答案(2)|浏览(132)

下面是我的代码大纲(保留一些细节)。基本上,我只是想在单击按钮时发出两个类似的API请求,然后有一个函数可以处理这两个请求的结果,但我无法弄清楚。

class myClass extends Component {

      constructor(props) {
        super(props);
        this.API_KEY_ONE = ‘firstapikey’
        this.API_KEY_TWO = ‘secondapikey’
        this.state = {
           city: 'undefined',
           state: 'undefined'
        }
      }

callOne() {
    this.REQUEST_URL = 'https://api.wunderground.com/api/' + this.API_KEY_ONE +    '/geolookup/conditions/astronomy/forecast/q/.json';

    fetch(this.REQUEST_URL).then((response) => response.json()).then((responseData)  => {

       this.setState({
        city: responseData.location.city
        });

    }).done();
}

 callTwo() {
      this.REQUEST_URL = 'https://api.DifferentSite.com/api/' + this.API_KEY_TWO +  '/geolookup/conditions/astronomy/forecast/q/.json';

      fetch(this.REQUEST_URL).then((response) => response.json()).then((responseData) => {

         this.setState({
        state: responseData.location.state
         });

     }).done();
}

// where to put this? when both requests finish, pass both to new component

this.props.navigator.push({
    title: 'Forecast',
    component: Forecast,
    passProps: {city: this.state.city, state: this.state.state}
  });

getForecast() {
     this.callOne();
     this.callTwo();
}

<TouchableHighlight onPress={() => this.getForecast()} />

字符串

yduiuuwa

yduiuuwa1#

你可以继续使用.then(),所以它应该是这样的:

callBoth(){
    var request_1_url = 'https://api.wunderground.com/api/' + this.API_KEY_ONE +    '/geolookup/conditions/astronomy/forecast/q/.json';
    var request_2_url = 'https://api.DifferentSite.com/api/' + this.API_KEY_TWO +  '/geolookup/conditions/astronomy/forecast/q/.json';

    fetch(request_1_url).then((response) => response.json()).then((responseData)  => {
        this.setState({
            city: responseData.location.city
        });
    }).then(()=>{
        fetch(request_2_url).then((response) => response.json()).then((responseData) => {
         this.setState({
            state: responseData.location.state,
            isFinish: true
         });
     }).done();
    }).done();
}

字符串

osh3o9ms

osh3o9ms2#

1)看起来你正在使用citystate作为passProp,并且不打算刷新currentView,所以也许你应该使用它们作为当前组件的变量。
2)您可以简单地使用一个变量来记录抓取的状态。与设置_finish = 0类似,当获取city时,_finish = _finish + 1,并验证_finish是否等于2。当获取state时,执行相同的验证。

fetch(...){
   // if _finish is equals 2, navigator push.
}

字符串
3)或者你可以不使用额外的变量:

fetch(...){
   if (this._city && this._state){
      // navigator push
   }
}

相关问题