2016-11-14 70 views
2

我需要一些在我的反應應用程序中使用Axios的助手。我將它與地理位置結合使用以獲取用戶位置,並將其用於與Axios的api通話。Axios獲取反應

我的代碼是:

componentDidMount() { 
if (navigator.geolocation){ 

    function success(position) { 
    var latitude = position.coords.latitude; 
    var longitude = position.coords.longitude; 
    var th = this; 
    this.serverRequest = 
     axios.get(`https://api.darksky.net/forecast/APIKEY/`+latitude+`,`+longitude+`?units=auto`) 
     .then(result => { 
      th.setState({ 
      daily: result.data.daily.data, 
      loading: false, 
      error: null 
      }); 
     }) 
     .catch(err => { 
     // Something went wrong. Save the error in state and re-render. 
     this.setState({ 
      loading: false, 
      error: err 
     }); 
     }); 
    }; 
    function error() { 
    console.log('geolocation error') 
    }; 
    navigator.geolocation.getCurrentPosition(success, error); 
} 
} 

但我最終的誤差Uncaught TypeError: Cannot set property 'serverRequest' of undefined

回答

7

success被稱爲回調,其this值不會是正確的 - 你的情況是undefined。您可以通過在您的回撥功能上使用bind來解決此問題:

navigator.geolocation.getCurrentPosition(success.bind(this), error); 
+1

您已經度過了我的一天。謝謝! – frisk0