我试图从componentDidMount(或渲染)函数中获取区域状态,但它失败了。你知道为什么吗?
这是我的代码:
constructor(props) {
super(props);
navigator.geolocation.getCurrentPosition(
(position) => {
this.region = {
latitude: position.coords.latitude,
latitudeDelta: 0.005,
longitude: position.coords.longitude,
longitudeDelta: 0.005,
}
console.log("location from constructor:", this.region);
},
(error) => alert(error.message),
{enableHighAccuracy: true, timeout: 20000, maximumAge: 2000}
);
this.state = {
region: this.region
}
}
componentDidMount() {
console.log("location from componentDidMount:", this.state.region);
}
以下是我的日志:
location from componentDidMount: undefined
location from constructor: Object {latitude: 48.8732, latitudeDelta: 0.005, longitude: 2.402855, longitudeDelta: 0.005}
答案 0 :(得分:1)
navigator.geolocation.getCurrentPosition是一个异步函数。异步函数完成并调用适当的成功或失败回调所花费的时间是不确定的。不保证在componentDidMount调用之前发生。