我正在尝试在我的react应用程序中使用地理定位。
我得到经度和纬度在控制台,但我得到错误:
Unhandled Rejection (TypeError): Cannot read property 'coords' of undefined.
这是我的代码:
const [location, setLocation]= useState({
coordinates: {lat:"", long:""}
});
const onSucces = location=>{
setLocation({
coordinates:{
lat: location.coords.latitude,
long: location.coords.longitude
}
})
};
useEffect(()=>{
if (!("geolocation" in navigator)){
console.log("Geolocation is not supported")
}
navigator.geolocation.getCurrentPosition(onSucces)
}, []);
console.log(location)
const getTeamLeadersLocation = async () => {
const result = await client.post('api/team/location',
{
"Location":{
"coords":{
"latitude":location.coordinates.lat,
"longitude":location.coordinates.long,
}
}
}
)
if(!result.ok){
console.log(result, result.originalError, result.problem, result.status);
return;
}
onSucces()
console.log(result)
}
useEffect(() => {
getTeamLeadersLocation();
}, []);
请帮助。
在您的getTeamLeadersLocation()
函数中,您正在调用onSuccess
而没有所需的location
参数。所以它尝试访问未定义的coords
。因此你得到了错误。此外,您已经调用了状态location
,并且该变量可能会被遮蔽,因此您应该重命名其中一个。这也减少了调试时的困惑。