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

React自定义useGeoLocation Hook获取定位时解构返回undefined求助

解决React useGeoLocation Hook返回Promise无法获取位置的问题

问题根源

你定义的useGeoLocation被标记为async函数,这违反了React Hook的核心规则:Hook必须是同步函数。async函数执行后会返回一个Promise对象,而非直接返回状态值,这就是你调用时得到Promise、解构location结果为undefined的原因。

修正后的Hook代码

移除async关键字,通过useState和useEffect的组合处理异步地理位置请求即可:

import { useState, useEffect } from "react";

const useGeoLocation = () => {
    const [location, setLocation] = useState({
        loaded: false,
        accuracy: '',
        coordinates: { lat: "", lng: "" },
        error: null
    });

    // 重命名参数避免和外部状态变量混淆
    const onSuccess = (position) => {
        setLocation({
            loaded: true,
            accuracy: position.coords.accuracy,
            coordinates: {
                lat: position.coords.latitude,
                lng: position.coords.longitude,
            },
            error: null
        });
    };

    const onError = (error) => {
        setLocation({
            loaded: true,
            accuracy: '',
            coordinates: { lat: "", lng: "" },
            error: {
                code: error.code,
                message: error.message,
            },
        });
    };

    useEffect(() => {
        if (!("geolocation" in navigator)) {
            onError({
                code: 0,
                message: "Geolocation not supported",
            });
            return;
        }

        navigator.geolocation.getCurrentPosition(onSuccess, onError);
    }, []);

    return location;
};

export default useGeoLocation;

组件中正确使用方式

直接调用Hook并解构返回的状态对象,根据loaded和error状态渲染对应内容:

function LocationComponent() {
  const { loaded, coordinates, error, accuracy } = useGeoLocation();

  if (!loaded) {
    return <div>正在获取位置...</div>;
  }

  if (error) {
    return <div>获取位置失败:{error.message}</div>;
  }

  return (
    <div>
      当前位置:
      纬度 {coordinates.lat},经度 {coordinates.lng}
      <br />
      定位精度:{accuracy} 米
    </div>
  );
}

关键修改说明

  1. 移除async关键字,让Hook同步返回状态对象,符合React Hook规则
  2. 重命名onSuccess的参数为position,避免和外部状态变量location混淆
  3. 在onError中重置coordinates和accuracy字段,保证状态结构一致性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 19:55:10