2017-07-21 48 views
0

我想獲得一個json文件作爲回報。我收到了一個承諾,回覆在React本地獲取電話

這是一個取功能我使用

handleApi(){ 
    return 
     fetch('https://facebook.github.io/react-native/movies.json') 
      .then((response) => response.json()) 
       .then((responseJson) => { 
      return responseJson.movies; 
     }) 
} 

這個函數被調用上的按鈕單擊事件。

handleSubmit() { 
    console.log(
     this.handleApi(); 
    ) 

,但我得到這個承諾在返回的對象不是預期的數據

無極{_40:0,_65:0,_55:空,_72:空} _40:0_55:null_6​​5 :0_72:null__proto__:對象

+1

'fetch'返回一個承諾,它是如何工作。您需要將'console.log'移動到'this.handleApi()。然後(console.log)'中 –

回答

0

更簡化

handleApi(){ 
    return 
     fetch('https://facebook.github.io/react-native/movies.json') 
      .then(response => 
       response.json().then(jsonObj => return jsonObj.movies) 
      ) 
} 

然後在handleSubmit

handleSubmit() { 
    this.handleApi().then(movies => { 
     console.log('Print list of movies:', movies); 
    }); 
) 
0

請更新您的代碼如下:

handleApi(){ 
return 
    fetch('https://facebook.github.io/react-native/movies.json') 
     .then((response) => response.json()) 
     .then((responseJson) => { 
      return responseJson.movies; 
     }) 
} 

handleSubmit() { 
this.handleApi().then(function(movies) { 
    console.log('Print list of movies:', movies); 
}); 
}