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

Expo构建的React Native应用位置信息注册与更新失败问题求助

Expo构建的React Native应用位置信息注册与更新失败问题求助

各位好呀!我现在用Expo开发React Native应用,最近在做位置信息的注册和字段更新功能,但怎么都没法正常运行,实在找不到问题出在哪,来求助大家了😭

先说说我的情况:我已经实现了位置权限请求的逻辑,权限获取成功后会调用获取当前位置的方法,但在获取到位置信息后,无论是把数据上传到Firebase(就是代码里的那个URL对应的数据库),还是更新本地的状态数组,这些操作都没生效。

我的代码片段如下:

import * as Location from 'expo-location';
const URL = {
    CREATE_CURRENT_LOCATION:'https://sayhellotobike-native-ios-default-rtdb.firebaseio.com'
}

export const requestLocationPermission = async (setLocationCallBack,myCurrentLocationArray,setIsMapReady) => {
try {
    const { status } = await Location.requestForegroundPermissionsAsync();
    if (status === 'granted') {
        // 位置情報の取得処理を実行する
        getCurrentLocation(setLocationCallBack,myCurrentLocationArray,setIsMapReady);
        
    } else {
        console.log('Location permission denied');
    }
    } catch (error) {
        console.error('Error requesting location permission:', error);
    }
};

export const getCurrentLocation = async (setLocationCallBack,myCurrentLocationArray,setIsMapReady) => {
    try {
        const { coords } = await Location.getCurrentPositionAsync({
            accuracy: Location.Accuracy.High
        });
        // 这里我尝试把获取到的经纬度添加到本地数组,同时上传到Firebase数据库
        const newLocation = {
            lat: coords.latitude,
            lng: coords.longitude
        };
        // 更新本地状态
        setLocationCallBack([...myCurrentLocationArray, newLocation]);
        setIsMapReady(true);
        // 上传到数据库
        await fetch(`${URL.CREATE_CURRENT_LOCATION}/locations.json`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(newLocation)
        });
    } catch (error) {
        console.error('Error getting current location:', error);
    }
};

我已经做了这些调试:

  • 确认权限已经成功获取,控制台没有权限拒绝的日志
  • 打印coords的值,确实能拿到正确的经纬度
  • 检查Firebase的规则,已经设置了公开读写(测试阶段)

但就是本地数组没有更新,数据库里也没有新的数据写入,有没有大佬能帮我分析一下可能的问题点?比如状态更新的方式不对?或者fetch请求有隐藏的错误没被捕获到?

备注:内容来源于stack exchange,提问作者谷口祐人

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.17 10:39:36