首页 > 解决方案 > geocodeAync 错误阻止功能拍摄

问题描述

在此处输入图像描述] 1 rybody 我正在构建一个基于位置的组件,需要获取城市名称以通过获取 API 请求来传递它,就像这样 axios.get( /${cityName}/JSON);

在我编写的组件中,有时运行良好,但大部分时间都给出了错误(null 不是对象(评估'location.coords')])

如何克服它以及如何使用纬度和经度或任何其他方法单独获取 cityName

import React, { useState, useEffect } from 'react';
import { Platform, Text, View, Button } from 'react-native';
import Constants from 'expo-constants';
import * as Location from 'expo-location';


export default function App() {
  const [location, setLocation] = useState(null);
  const [errorMsg, setErrorMsg] = useState(null);
  const [city, setCity] = useState('');

 const getLocation = async () => {
    let { status } = await Location.requestPermissionsAsync();
    if (status !== 'granted') {
      setErrorMsg('Permission to access location was denied');
    }

    let location = await Location.getCurrentPositionAsync({});
    setLocation(location);
    console.log(location);
  }

  const getCity = async () => {
      const place = await Location.reverseGeocodeAsync({
          latitude : location.coords.latitude,
          longitude : location.coords.longitude
      });
      setCity(place.city);
      console.log(city);
  }

    useEffect(() => {
        getLocation() , getCity();
    } , []);



  let text = 'Waiting..';
  if (errorMsg) {
    text = errorMsg;
  } else if (location) {
    text = JSON.stringify(location);
  }

  return (
    <View >
        <Text> </Text>
        <Button title = 'press' 
        onPress = {getCity}
        />
    </View>
  );
}

标签: reactjsreact-nativegeolocationlocationexpo

解决方案


所以,问题是当组件第一次在此处重新渲染时,您正在调用 getCity ,而没有位置对象:

useEffect(() => {
    getLocation() , getCity();
} , []);

这两个函数都是异步的,但这并不能保证它们会按那个顺序发生。此外,会发生什么是函数并行运行,这会导致你的错误。

您在这里有多个选项:-您可以将多个承诺链接在一起以确保执行顺序-您可以从上述 useEffect 中删除 getCity 调用,并仅在 getLocation 调用完成后调用它(不允许用户在此之前进行交互)


推荐阅读