使用React Native获取多个API请求

时间:2015-10-13 14:01:38

标签: api promise fetch react-native react-router

这是我的代码大纲(保留一些细节)。基本上我只想在单击一个按钮时发出两个类似的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()} />

2 个答案:

答案 0 :(得分:4)

您可以继续.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();
}

答案 1 :(得分:0)

1)您似乎使用citystate作为passProps而不是刷新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
   }
}
相关问题