Axios fetch in react

时间:2016-11-14 21:33:44

标签: javascript reactjs axios

在我的反应应用程序中使用Axios需要一些帮助。我将它与地理位置结合使用以获取用户位置,并在与Axios的api调用中使用它。

我的代码是:

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

1 个答案:

答案 0 :(得分:7)

success被称为回调时,其this值不会是正确的 - 在您的情况下它是undefined。您可以在回调函数上使用bind来解决此问题:

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