[英]How to destructure object from custom hook to getCurrentPosition for user's location
I have created a simple custom react hook to get users location.我创建了一个简单的自定义反应挂钩来获取用户位置。
import { useState, useEffect } from "react";
const useGeoLocation = async () => {
const [location, setLocation] = useState({
loaded: false,
accuracy: '',
coordinates: { lat: "", lng: "" },
error: null
});
// console.log(location)
const onSuccess = (location) => {
setLocation({
loaded: true,
accuracy: location.accuracy,
coordinates: {
lat: location.coords.latitude,
lng: location.coords.longitude,
},
});
};
const onError = (error) => {
setLocation({
loaded: true,
error: {
code: error.code,
message: error.message,
},
});
};
useEffect(() => {
if (!("geolocation" in navigator)) {
onError({
code: 0,
message: "Geolocation not supported",
});
}
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}, []);
return location;
};
export default useGeoLocation;
However when I try to destructure location by calling the hook in my functional component.但是,当我尝试通过调用我的功能组件中的钩子来解构位置时。 It is returning undefined.它返回未定义。
Somewhere in my functional component在我的功能组件中的某处
const { location } = useGeoLocation()
console.log(location)
I have tried to console log the whole query with我试图用控制台记录整个查询
const location = useGeoLocation()
console.log(location)
However I am getting a promise that is fullfilled after sometime and my location object is present inside the result but I am not able to get this value out.然而,我得到一个 promise,它在一段时间后被填满,我的位置 object 出现在结果中,但我无法得到这个值。
I am noob and expecting help from experts.我是菜鸟,期待专家的帮助。
Please stop adding async
everywhere.请停止在任何地方添加async
。 It should be used only if you want to use await
.仅当您想使用await
时才应使用它。 async
makes your function return a promise async
使您的 function 返回 promise
import { useState, useEffect } from "react";
const useGeoLocation = () => {
const [location, setLocation] = useState({
loaded: false,
accuracy: '',
coordinates: { lat: "", lng: "" },
error: null
});
// console.log(location)
const onSuccess = (location) => {
setLocation({
loaded: true,
accuracy: location.accuracy,
coordinates: {
lat: location.coords.latitude,
lng: location.coords.longitude,
},
});
};
const onError = (error) => {
setLocation({
loaded: true,
error: {
code: error.code,
message: error.message,
},
});
};
useEffect(() => {
if (!("geolocation" in navigator)) {
onError({
code: 0,
message: "Geolocation not supported",
});
}
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}, []);
return location;
};
export default useGeoLocation;
Usage用法
const location = useGeoLocation()
console.log(location)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.