componentDidMount、getCurrentPosition 延迟
componentDidMount, getCurrentPosition delay
我使用这样的模式来获取用户的当前位置:
componentDidMount() {
let lat, lon;
navigator.geolocation.getCurrentPosition(function(location) {
lat = location.coords.latitude;
lon = location.coords.longitude;
});
setTimeout(() => {
this.setState({
lat,
lon
})
console.log(this.state.lon, this.state.lat);
}, 1000);
}
它确实有效,但看起来 "patchy" 因为 setTimeout
。
核心问题是在没有 setTimeout
的情况下获取位置和控制台抛出 undefined
的一些延迟。
我尝试了其他几种方法来修复它,但都失败了:
navigator.geolocation.getCurrentPosition(function(location) {
this.setState({
lat: location.coords.latitude,
lon: location.coords.longitude
})
}).bind(this);
例如 和谦虚 let _this = this
。
请问,有没有更明智的方法setState
,基于地理位置?
如评论中所述,您可以稍微移动绑定或使用箭头功能:
componentDidMount() {
navigator.geolocation.getCurrentPosition(function (location) {
this.setState({
lat: location.coords.latitude,
lon: location.coords.longitude
})
}.bind(this));
// OR
navigator.geolocation.getCurrentPosition(location => {
this.setState({
lat: location.coords.latitude,
lon: location.coords.longitude
})
});
}
我使用这样的模式来获取用户的当前位置:
componentDidMount() {
let lat, lon;
navigator.geolocation.getCurrentPosition(function(location) {
lat = location.coords.latitude;
lon = location.coords.longitude;
});
setTimeout(() => {
this.setState({
lat,
lon
})
console.log(this.state.lon, this.state.lat);
}, 1000);
}
它确实有效,但看起来 "patchy" 因为 setTimeout
。
核心问题是在没有 setTimeout
的情况下获取位置和控制台抛出 undefined
的一些延迟。
我尝试了其他几种方法来修复它,但都失败了:
navigator.geolocation.getCurrentPosition(function(location) {
this.setState({
lat: location.coords.latitude,
lon: location.coords.longitude
})
}).bind(this);
例如 和谦虚 let _this = this
。
请问,有没有更明智的方法setState
,基于地理位置?
如评论中所述,您可以稍微移动绑定或使用箭头功能:
componentDidMount() {
navigator.geolocation.getCurrentPosition(function (location) {
this.setState({
lat: location.coords.latitude,
lon: location.coords.longitude
})
}.bind(this));
// OR
navigator.geolocation.getCurrentPosition(location => {
this.setState({
lat: location.coords.latitude,
lon: location.coords.longitude
})
});
}