簡體   English   中英

geocodeAync 錯誤阻止 function 拍攝

[英]Error with geocodeAync preventing function to shoot

在此處輸入圖像描述] 1 rybody 我正在構建一個基於位置的組件需要獲取城市名稱以通過 API 的獲取請求來傳遞它,就像這樣 axios.get( /${cityName}/JSON );

在我寫的組件中,有時運行良好,但大部分時間都給出了該錯誤( null 不是 object (評估'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>
  );
}

所以,問題是當組件第一次在此處重新渲染時調用 getCity 而沒有位置 object:

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

這兩個函數都是異步的,但這並不能保證它們會按那個順序發生。 此外,會發生什么是函數並行運行,這會導致你的錯誤。

您在這里有多個選項: - 您可以將多個 Promise 鏈接在一起以確保執行順序 - 您可以從上述 useEffect 中刪除 getCity 調用,並僅在 getLocation 調用完成后調用它(不允許用戶在此之前進行交互)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM