自定义Hook调用expo-location出现null is not an object报错如何解决
问题解决方法
报错根因
你调用Location.getLastKnownPositionAsync()时,如果设备没有缓存的历史定位记录,该接口会直接返回null。你直接对返回结果解构coords属性,就会触发null is not an object的报错。
修复方案
对定位返回结果增加非空判断,历史缓存位置为空时兜底调用实时定位接口即可,修改后的完整代码如下:
import * as Location from "expo-location"; import { useEffect, useState } from "react"; export default useLocation = () => { const [location, setLocation] = useState(null); const getLocation = async () => { try { const { granted } = await Location.requestForegroundPermissionsAsync(); if (!granted) return; // 先尝试获取历史缓存位置 let position = await Location.getLastKnownPositionAsync(); // 历史位置为空时调用接口实时获取定位 if (!position) { position = await Location.getCurrentPositionAsync({}); } const { latitude, longitude } = position.coords; setLocation({ latitude, longitude }); } catch (error) { console.log("定位获取失败:", error); } }; useEffect(() => { getLocation(); }, []); return location; };
额外注意事项
- 业务侧使用返回的
location时,必须先判断非空再访问属性,示例如下:
const location = useLocation(); if (location) { // 业务逻辑 console.log(location.latitude, location.longitude) }
- iOS设备需要确保
app.json中已配置NSLocationWhenInUseUsageDescription权限说明 - Android设备需要确保
app.json中已配置ACCESS_COARSE_LOCATION或ACCESS_FINE_LOCATION权限
内容的提问来源于stack exchange,提问作者Saddy Ahmed
相关产品推荐
相关产品推荐

