使用导航器地理定位与反应堆

时间:2016-10-01 21:57:56

标签: javascript reactjs geolocation

我正在尝试显示地理位置变量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

1 个答案:

答案 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();
},