提问者:小点点

React Native-expo getCurrentPositionAsync不工作


所以我试图从expo-place获取用户当前的co-oridnates,并在我的android手机上使用expo客户端进行测试。下面的代码将状态记录为已批准,但纬度和经度没有更新,在iphone上我收到以下错误:

[未处理的promise拒绝:错误:请求失败,状态码为400]在node_modules/axios/lib/core/createError. js:15:17 in createError atnode_modules/axios/lib/core/settel.js:16:9 in setleLoad atnode_modules/react-native/Library/Network/XMLHttpRequest.js:601:4 in setReadyState atnode_modules/react-native/Library/Network/XMLHttpRequest.js:396:6 in__didCompleteResponseatnode_modules/react-native/Library/供应商/发射器/_EventEmitter.js:135:10 in EventEmitter#emit

代码:

    const [latitude, setLatitude] = useState();
    const [longitude, setLongitude] = useState();
    const getLocationAsync = async () => {
        let { status } = await Location.requestForegroundPermissionsAsync();
    
        if (status === 'granted') {
            console.log('Approved!');
            return Location.getCurrentPositionAsync({ enableHighAccuracy: true });
        } else {
           console.log('Rejected!');
           throw new Error('Location permission not granted');
        }
    }
    useEffect(() => {
        const location = getLocationAsync();
        setLatitude(location.latitude);
        setLongitude(location.longitude);
    }, []);

共1个答案

匿名用户

getLocationAsync是Promise函数。

您可以更改此代码

 useEffect(() => {
    (async () => {
      const { status } = await Location.requestForegroundPermissionsAsync();
    
        if (status === 'granted') {
           console.log('Approved!');
           const location = await Location.getCurrentPositionAsync({ enableHighAccuracy: true });
           setLatitude(location.latitude);
           setLongitude(location.longitude);
        } else {
           console.log('Rejected!');
           throw new Error('Location permission not granted');
        }
    })();
  }, []);