首页 > 解决方案 > 基于用户位置的 React Native API 调用

问题描述

我刚刚开始使用 react 和 react native 我的目标是获取用户位置,并根据位置坐标进行 API 调用并显示结果。我哪里出错了?我正在使用带有 aqicn API 库的 EXPO 项目。

这是代码。

import React,{ useState , useEffect} from 'react';
import { StyleSheet, Text, View ,Button} from 'react-native';
import * as Location from 'expo-location';
import Constants from 'expo-constants';
import axios from 'axios';
//First get location - Done
//get latitude & longitude - Done
//Call the api with latitude and longitude
//Display results

export default function HomeScreen({navigation}) {

  const [location, setLocation] = useState(null);
  const [errorMsg, setErrorMsg] = useState(null);
  //Lat and Long

  const [latitude, setLatitude] = useState(null);
  const [longitude , setLongitude]= useState(null);
  const [data, setData] = useState([]);


  useEffect(() => {
    (
      async () => {
      let { status } = await Location.requestPermissionsAsync();
      if (status !== 'granted') {
        setErrorMsg('Permission Denied');
        return;
      }

      let location = await Location.getCurrentPositionAsync({});
      setLocation(location);
      //Changes
      setLatitude(location.coords.latitude);
      setLongitude(location.coords.longitude);
            
    })();
  }, []);


    
    const la=latitude;
    const lo=longitude;
    
    console.log(la , lo);

    let res = fetch("https://api.waqi.info/feed/geo:"+ la +";"+ lo +"/?token=ac3a71fc80931abd95ede14c2040f0678f578703")
    .then((response) => response.json())
    .then((json) => setData(json.data))
    .catch((error) =>console.log(error))
    
  

     console.log(data);
   

    return (
    <View style={styles.container}>
      <Text style={styles.paragraph}></Text>
    </View>
  );
}





   const styles= StyleSheet.create({
     container: {
       padding:20,
       marginTop:15,
       margin:10,

     },
     paragraph : {
       padding:20,
       marginTop:5,
     }


   });

标签: reactjsreact-nativegeolocationexpo

解决方案


我想我知道你的问题是什么。仅当您填写了纬度和经度状态时,您才必须执行请求。您可以使用钩子 useEffect 确保这一点。您的代码必须是这样的:

 useEffect(() => {
    /** Creating an useEffect like this
you ensure that the latitude and longitude state are filled. Therefore,
your request is going to work :).
**/
    async function anyNameFunction() {
    let res = fetch("https://api.waqi.info/feed/geo:"+ latitude +";"+ longitude +"/?token=ac3a71fc80931abd95ede14c2040f0678f578703")
    .then((response) => response.json())
    .then((json) => setData(json.data))
    .catch((error) =>console.log(error))
     console.log(data);
    }    
    anyNameFunction();
  }, [latitude, longitude]);

如果您有任何疑问,请随意询问更多:)。等待您的反馈,如果答案是正确的,请竖起大拇指!


推荐阅读