2016-10-01 7 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

デフォルトで

、コンポーネントの状態や小道具が変化し、あなたのコンポーネントが再レンダリングされます。

ので:あなたはstateを使用しない場合

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>; 
    } 
}); 

、あなたのハンドラメソッドの最後で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

関連する問題