Javascript 如何在React中调用componentDidMount中的地理位置
因此,我试图使用axios与HTML5Geolocation一起构建一个api 我将它放在componentDidMount中,希望它至少能在console.log中工作。使用async记录结果,并最终将状态设置为countryJavascript 如何在React中调用componentDidMount中的地理位置,javascript,html,reactjs,Javascript,Html,Reactjs,因此,我试图使用axios与HTML5Geolocation一起构建一个api 我将它放在componentDidMount中,希望它至少能在console.log中工作。使用async记录结果,并最终将状态设置为country componentDidMount(){ async onLoad() { if (window.navigator.geolocation) { window.navigator.geolocation.getCurren
componentDidMount(){
async onLoad() {
if (window.navigator.geolocation) {
window.navigator.geolocation.getCurrentPosition(
position => {
const response = axios.get('http://ws.geonames.org/countryCode' , {
lat: position.coords.latitude,
lng: position.coords.longitude,
type: 'JSON'
});
console.log('here is the response >>>>', response.countryName);
this.setState({ country: response.countryName })
});
}
}
}
然而,这目前不起作用。我正在使用我的API
你知道我在代码上做错了什么吗?你正在声明
onLoad
方法但没有调用它,请删除声明并直接调用代码,因为在componentDidMount
componentDidMount() {
if (window.navigator.geolocation) {
window.navigator.geolocation.getCurrentPosition(
position => {
const response = axios.get('http://ws.geonames.org/countryCode', {
lat: position.coords.latitude,
lng: position.coords.longitude,
type: 'JSON'
});
console.log('here is the response >>>>', response.countryName);
this.setState({
country: response.countryName
})
});
}
}
如@Shridhar Sharma所述,移除负载 代码中缺少
wait
。如果没有wait表达式,异步函数的执行将不会等待承诺解析
还有一件事要记住,即使浏览器支持地理定位,也可能会出现其他错误,例如权限被拒绝、位置不可用和超时。看更多
你到底面临着什么样的挑战?这段代码有错误吗?
componentDidMount() {
if (window.navigator.geolocation) {
window.navigator.geolocation.getCurrentPosition( async (position) => {
const response = await axios.get("http://ws.geonames.org/countryCode", {
lat: position.coords.latitude,
lng: position.coords.longitude,
type: "JSON"
});
console.log("here is the response >>>>", response.countryName);
this.setState({ country: response.countryName });
}, (e) => {
// other errors appear here
console.log(e);
});
} else {
console.log("navigator not supported");
}
}