简体   繁体   English

geocodeAync 错误阻止 function 拍摄

[英]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.

相关问题 Function 包装防止 componentDidUpdate? - Function wrapper preventing componentDidUpdate? TSLint - 防止错误:密钥不按字母顺序排序 - TSLint - Preventing error: The key is not sorted alphabetically 防止 reactjs 中 axios 错误的默认事件 - preventing default event on axios error in reactjs Nextjs getInitialProps 错误阻止在 Netlify 上构建 - Nextjs getInitialProps error preventing build on Netlify 防止 ReactJS 箭头函数 class 属性上的 ESLint “no-undef” - Preventing ESLint “no-undef” on ReactJS arrow-function class properties 重新呈现整个播放列表的文本框上的onBlur函数阻止了切换至下一个文本框的功能 - onBlur function on a textbox that rerenders the whole playlist is preventing the ability to tab over to the next textbox 是什么阻止了这个 function 执行其中的钩子? 反应机制如何使这成为不可能? - What is preventing this function from executing the hooks inside of it? What about react mechanics makes this impossible? React render函数防止每次调用时创建新的canvas元素-Charts.js - React render function preventing creating new canvas element on each time invoked - Charts.js 如何确保WebSocket消息是JSON字符串,防止JSON.parse错误? - How to ensure a WebSocket message is JSON string, preventing JSON.parse error? .filter函数“不是函数”错误 - .filter function “is not a function” error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM