You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用useGeolocated更新React状态时为何出现undefined?

问题原因及解决方案

1. useEffect依赖项错误

你的useEffect监听的是longitude和latitude这两个状态变量,但这两个变量是你要更新的目标,初始值为null,当coords加载完成后,这两个状态没发生变化的话,useEffect不会触发。正确的依赖应该是coords,因为你需要在coords数据更新时同步状态。

2. 未处理coords初始为undefined的情况

useGeolocated在获取地理位置前,coords可能是undefined或null,直接访问coords.latitude会抛出undefined错误,需要先判断coords是否存在。

3. 状态更新函数拼写错误

setLatitiude多写了一个字母i,正确的应该是setLatitude,拼写错误会导致状态无法正常更新。


修正后的代码示例

const [latitude, setLatitude] = useState(null)
const [longitude, setLongitude] = useState(null)
    
const { coords, isGeolocationAvailable, isGeolocationEnabled } = useGeolocated({
    positionOptions: {
        enableHighAccuracy: false
    },
    userDecisionTimeout: 5000
})

useEffect(() => {
    // 先判断coords是否存在,避免undefined错误
    if (coords) {
        setLatitude(coords.latitude)
        setLongitude(coords.longitude)
    }
}, [coords]) // 依赖改为coords,监听其变化

内容的提问来源于stack exchange,提问作者Hadi Zouhbi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 15:54:25