【发布时间】:2021-01-04 14:06:29
【问题描述】:
我是 React native 的新手,并试图解构我使用 map 函数从我的 API 调用中获得的 json 响应,并且不知何故它给了我上述错误。我想使用文本组件显示 aqi 和主要污染物。我正在使用 AQICN API。
import React,{ useState , useEffect} from 'react';
import { StyleSheet, Text, View ,ActivityIndicator, ScrollView,FlatList} from 'react-native';
import * as Location from 'expo-location';
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([]);
const [loader, setLoader]=useState(true);
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;
async function AqicnApiCall() {
let res = await 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))
}
AqicnApiCall();
})();
}, [latitude, longitude]);
//const obj=JSON.stringify(data);
return (
<ScrollView style={styles.container}>
{
data.map((d) =>{
console.log(d);
return(
<Text style={styles.container}>{d.data.aqi}</Text>
)
})
}
</ScrollView>
);
}
const styles= StyleSheet.create({
container: {
padding:20,
marginTop:15,
margin:10,
},
paragraph : {
padding:20,
marginTop:5,
}
});
这是 API 响应,我需要主要污染物和 aqi。
【问题讨论】:
-
数据是数组还是对象?似乎是一个对象。我错了吗?
-
我的错。它是一个对象。你能指导我吗?我尝试了其他不起作用的方法。
标签: reactjs react-native api geolocation