[英]why is my state not being set to the variable lat?
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)
When I console.log the variable I get a number but why cant I use it as a value in state. 当我console.log变量时,我得到一个数字,但是为什么我不能使用它作为状态值。 Even putting it inside an array makes no difference. 即使将其放在数组中也没有区别。
it should be this: 应该是这样的:
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>
)
}
}
You change the state by using setState()
您可以使用setState()
更改状态
navigator.geolocation.getCurrentPosition(function(position) {
this.setState({
lat: position.coords.latitude,
lon: position.coords.longitude
});
console.log(typeof lat)
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.