【问题标题】:JS - geolocation function error , while everything works OKJS - 地理定位功能错误,而一切正常
【发布时间】:2018-05-09 21:54:01
【问题描述】:

我正在做天气应用程序,它具有 getCoords 功能,一旦“找到我!”就会激活按钮被点击:

getCoords(e){
e.preventDefault();
if(navigator.geolocation){
  navigator.geolocation.getCurrentPosition((position) =>{
    const long = position.coords.longitude,
          lat = position.coords.latitude;
          console.log(`long ${long} and lat ${lat}`);
    this.setMessage('http://api.openweathermap.org/data/2.5/forecast?lat='+lat+'&lon='+long+"&APPID=mykey");
  }).bind(null,this);
}
}

由于我对结果感到满意,它给出了它并且它确实像我预期的那样工作,我在控制台中遇到了很多错误,这让我感到有点担心。 火狐:

TypeError: navigator.geolocation.getCurrentPosition(...) 未定义

chrome 和 Opera:

未捕获的类型错误:无法读取未定义的属性“绑定” 在 WeatherApp.getCoords (app.bundle.js?49cb1f92ba06aee2ea42:374)

歌剧:

加载资源失败:服务器响应状态为 404(未找到)

【问题讨论】:

  • .getCurrentPosition() 函数不会返回另一个函数,但您的代码编写时就像它一样。

标签: javascript reactjs geolocation xmlhttprequest


【解决方案1】:

你没有将 'this' 绑定到 tu 函数,而是它的返回值。

'bind' 是 Function 原型的一个方法。我不确定你为什么要使用绑定调用。只需删除它或在调用函数之前调用它。

【讨论】:

  • 我已经把它删除了,现在到处都可以了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-31
  • 1970-01-01
相关资源
最近更新 更多