在下面的代码中,将空数组作为useEffect的第二个参数时,它不返回值。但是删除第二个参数会得到结果。但它执行无限
const useCurrentLocation = (options: GeoOptions | null) => {
const [location, setLocation] = useState<GeoPosition | null>(null);
const [error, setError] = useState<GeoError | null>(null);
useEffect(() => {
const fetchLocation = async () => {
try {
const location: GeoPosition = await new Promise((resolve, reject) => {
getCurrentPosition((loc) => {
if (loc) {
resolve(loc)
}
}, (err) => {
reject(err)
setError(err)
}, options ? options : { enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 })
})
if (location !== null) {
setLocation(location);
}
else {
setLocation(null);
}
}
catch (err) {
setLocation(null);
return null;
}
}
fetchLocation()
})
return { location, error }
}