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

问题描述 投票:0回答:1

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

javascript reactjs geolocation
1个回答
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();
},
© www.soinside.com 2019 - 2024. All rights reserved.