2016-11-14 11 views
2

私の反応のアプリケーションでAxiosを使用するための助手が必要です。私はGeolocationと組み合わせて使用​​して、ユーザーの場所を取得し、Axiosでapi呼び出しで使用します。Axiosフェッチin反応

私のコードは次のとおりです。

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); 
} 
} 

しかしsuccessがコールバックとして呼び出されたとき、私はUncaught TypeError: Cannot set property 'serverRequest' of undefined

答えて

7

エラーになってしまい、そのthis値は右ではありません - あなたのケースではundefinedです。コールバック関数でbindを使用してこの問題を解決できます。

+1

あなたは私の一日を作っています。ありがとう! – frisk0

関連する問題