[英]Error with geocodeAync preventing function to shoot
enter image description here ] 1 rybody I am building a location based component need to take the city name to pass it through a get request for API to be like this axios.get( /${cityName}/JSON
);在此处输入图像描述] 1 rybody 我正在构建一个基于位置的组件需要获取城市名称以通过 API 的获取请求来传递它,就像这样 axios.get(
/${cityName}/JSON
);
in the component I am writing some times working well but most of the time is giving that error ( null is not an object (evaluating 'location.coords')] )在我写的组件中,有时运行良好,但大部分时间都给出了该错误( null 不是 object (评估'location.coords')])
How to get over that and how to get the cityName alone using latitude and longitude or whatever any other method如何克服它以及如何使用纬度和经度或任何其他方法单独获取 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>
);
}
So, the issue is that you are calling getCity when the component is first redered here without having the location object:所以,问题是当组件第一次在此处重新渲染时调用 getCity 而没有位置 object:
useEffect(() => {
getLocation() , getCity();
} , []);
Both functions are async, but that is not a guarantee that they will happen in that order.这两个函数都是异步的,但这并不能保证它们会按那个顺序发生。 Moreover, what happens is that the functions run in parallel and that leads to your error.
此外,会发生什么是函数并行运行,这会导致你的错误。
You have multiple options here: - you can chain together multiple promises to ensure order of execution - you can remove the getCity call from the above useEffect and call it only after the getLocation call is done (do not allow the user to Interact before that)您在这里有多个选项: - 您可以将多个 Promise 链接在一起以确保执行顺序 - 您可以从上述 useEffect 中删除 getCity 调用,并仅在 getLocation 调用完成后调用它(不允许用户在此之前进行交互)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.