首页
学习
活动
专区
圈层
工具
发布

Axios反应
EN

Stack Overflow用户
提问于 2016-11-14 21:33:43
回答 1查看 812关注 0票数 2

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

我的代码是:

代码语言:javascript
复制
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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-11-14 21:36:36

success作为回调被调用时,它的this值将不正确--在您的示例中是undefined。您可以通过在回调函数上使用bind来修复这个问题:

代码语言:javascript
复制
navigator.geolocation.getCurrentPosition(success.bind(this), error);
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40598186

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档