2016-10-01 28 views
0

我想显示地理位置变量position.coords.lat/long,我无法将值存储在全局范围内。下面是代码:使用导航器的地理定位与反应堆

var GeoLoco = React.createClass({ 
    lat: 0, 
    long: 0, 
    handler: function(position) { 
      this.lat = position.coords.latitude; 
      this.long = position.coords.longitude; 
      console.log("Lat,Long: "+this.lat+","+this.long); 
    }, 
    render: function() { 
      navigator.geolocation.getCurrentPosition(this.handler); 
      return <p>Lat,Long: {this.lat},{this.long}</p>; 
    } 
}); 

console.log显示位置数据,但this.latthis.long呈现为0

回答

0

即使你的变量的值发生变化,你必须重新渲染您的组件来更新你在做什么看到。 组件的state为您做到了。

More information here

默认情况下,当你的组件的状态或道具的变化,您的组件将重新呈现。

所以:

var GeoLoco = React.createClass({ 
    getInitialState: function() { 
    return {lat: 0, long: 0}; 
    }, 
    handler: function(position) { 
    this.setState({ 
     lat: position.coords.latitude, 
     long: position.coords.longitude 
    }); 
    }, 
    render: function() { 
    // If this.state.lat is not equal to 0, do not call again getCurrentPosition() 
    if (!this.state.lat) 
     navigator.geolocation.getCurrentPosition(this.handler); 
    return <p>Lat,Long: {this.state.lat},{this.state.long}</p>; 
    } 
}); 

如果你不想使用state,你可以在你的处理方法的末尾调用forceUpdate()

handler: function(position) { 
    this.lat = position.coords.latitude; 
    this.long = position.coords.longitude; 
    console.log("Lat,Long: "+this.lat+","+this.long); 
    this.forceUpdate(); 
}, 
+0

知道这是一个计时问题。非常感谢你'this.forceUpdate()'做了诀窍。 –

+0

请将此问题标记为已解决:) – Robiseb

相关问题