为什么我的状态没有设置为变量lat?

时间:2017-09-21 09:14:31

标签: javascript reactjs

let lon, lat;
let weather;
 if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(function(position) {
   lat = position.coords.latitude;
   lon = position.coords.longitude;
console.log(typeof lat)
 });
}
class Button extends React.Component{
state = {latt: lat}
		render(){
			return(
		<div>
{this.state.latt}
<h1>ss</h1>
</div>
			
)}}

class Appp extends React.Component {

	render(){
		return(
			<Button />
		)}
	}
ReactDOM.render(<Appp />, mountNode)

what i did

当我在console.log中变量时,我得到一个数字,但为什么我不能将它用作状态值。即使把它放在一个数组中也没什么区别。

2 个答案:

答案 0 :(得分:0)

它应该是这样的:

let lat, lon, weather;

class Calendar extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            lat: null,
            lon: null
        }
        this.updateLatLon = this.updateLatLon.bind(this);
    }
    updateLatLon(){
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition((position) => {
                this.setState(() => {
                    return {lat: position.coords.latitude, lon: position.coords.longitude}
                });
            });
        }
    }
    componentWillMount(){
        this.updateLatLon();
    }
    render(){
        return (
            <div>
                {this.state.lat}
            </div>
        )
    }
}

答案 1 :(得分:0)

您可以使用setState()

更改状态
navigator.geolocation.getCurrentPosition(function(position) {
    this.setState({
        lat: position.coords.latitude,
        lon: position.coords.longitude
    });
    console.log(typeof lat)
});