2017-01-18 31 views
0

我正嘗試使用FourSquare API在我的React App中返回位置信息。爲此,我使用這個有用的軟件包:https://www.npmjs.com/package/foursquarevenues如何在ES6/React中使用Promises時設置正確的'this'詞彙範圍

此軟件包使用承諾進行API調用。我的代碼如下所示調用軟件包。 API調用很好,我可以記錄響應 - 但是當我嘗試設置狀態時,它返回this.setState不是一個函數。我對ES6 Arrow函數非常陌生,但我嘗試重寫promise語句以使用新語法 - 因爲我認爲使用Arrow函數會自動將此上下文綁定到父範圍。但是這並沒有解決問題。我究竟做錯了什麼?任何幫助感謝!

foursquare.venues.getVenues(params) 
      .then(function(venues) { 
      const venueList = venues.response.venues 
       console.log(venueList); 
      this.setState({ 
       venues: venueList // this returns this.setState is not a function 
      }) 
      }) 
      .catch(err => { 
      console.log(err); 
      }); 
+4

'.then(venues => {... this.setState()...})'? –

+0

謝謝 - 我錯過了某種方式。讚賞 – ElJefeJames

回答

0
(arg1, arg2, arg3) => { this.doSomething(); } 

這符號創建誰從父this繼承自動功能。

另一種方法是將其保存在一個將被繼承的常量中。

const self = this; 
function exemple() { 
    self.doSomething(); 
}