代码之家  ›  专栏  ›  技术社区  ›  Seemax

componentDidMount,getCurrentPosition延迟

  •  0
  • Seemax  · 技术社区  · 6 年前

    我使用这样的模式来获取用户的当前位置:

    componentDidMount() {
           let lat, lon;
         navigator.geolocation.getCurrentPosition(function(location) {
             lat = location.coords.latitude;
             lon = location.coords.longitude;
     });
       setTimeout(() => {
        this.setState({
          lat,
          lon
        })
        console.log(this.state.lon, this.state.lat);
     }, 1000);
         }
    

    setTimeout . 核心问题在于获取位置和控制台抛出的延迟 undefined 没有 设置超时 我尝试了其他几种方法来修复它,但都失败了:

    navigator.geolocation.getCurrentPosition(function(location) {
        this.setState({
             lat: location.coords.latitude,
             lon: location.coords.longitude
         })
     }).bind(this);
    

    而且谦逊 let _this = this 例如 请问,有没有更明智的方法 setState ,基于地理位置?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Rick Jolly    6 年前

    如评论中所述,您可以稍微移动绑定或使用箭头函数:

    componentDidMount() {
        navigator.geolocation.getCurrentPosition(function (location) {
          this.setState({
            lat: location.coords.latitude,
            lon: location.coords.longitude 
          })
        }.bind(this));
    
        // OR
        navigator.geolocation.getCurrentPosition(location => {
          this.setState({
            lat: location.coords.latitude,
            lon: location.coords.longitude
          })
        });
    }