2016-10-01 2 views
0

Geolocation 변수 position.coords.lat/long을 표시하려고하는데 전역 값에 값을 저장하는 데 문제가 있습니다.탐색기에서 리액터로 Geolocation 사용

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