Saya baru mengenal Bereaksi asli dan mencoba merusak respons json yang saya dapatkan dari panggilan API saya menggunakan fungsi peta dan entah bagaimana itu memberi saya kesalahan di atas. Saya ingin menampilkan aqi dan polutan dominan menggunakan text componenet. Saya menggunakan API AQICN.

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,
     }


   });

Ini respon API, saya butuh polutan dan aqi yang dominan.

enter image description here

1
Subhodeep bhowmick 4 Januari 2021, 17:06

3 jawaban

Jawaban Terbaik

Aplikasi yang Berfungsi: Camilan Expo

enter image description here

Akses aqi dan dominentpol seperti di bawah ini:

 return (
    <ScrollView style={styles.container}>
      <Text style={styles.container}>AQI: {data?.aqi}</Text>
      <Text style={styles.container}>
        Dominant Pollutant: {data?.dominentpol}
      </Text>
    </ScrollView>
  );
}

Kode kerja penuh:

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) => {
            console.log('data: ', json.data);
            setData(json.data);
          })
          .catch((error) => console.log(error));
      }

      AqicnApiCall();
    })();
  }, [latitude, longitude]);

  //const obj=JSON.stringify(data);

  return (
    <ScrollView style={styles.container}>
      <Text style={styles.container}>AQI: {data?.aqi}</Text>
      <Text style={styles.container}>
        Dominant Pollutant: {data?.dominentpol}
      </Text>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container: {
    padding: 20,
    marginTop: 15,
    margin: 10,
  },
  paragraph: {
    padding: 20,
    marginTop: 5,
  },
});
0
Ketan Ramteke 4 Januari 2021, 17:56

Saya pikir beberapa d.data tidak terdefinisi atau nol. Silakan coba ini.

<ScrollView style={styles.container}>
    
    {
      data && data.map((d) =>{
        console.log(d);
        return(
          <Text style={styles.container}>{d?.data?.aqi}</Text>
        )
      })
    }
</ScrollView>
    
0
Vishwas Vaishnav 4 Januari 2021, 14:16

Karena data bukan array, dan saya melihat Anda hanya ingin menampilkan nilai aqi,

<ScrollView style={styles.container}>
    <Text style={styles.container}>{data?.aqi}</Text>
</ScrollView>

Pada tangkapan layar, tampaknya Anda hanya dapat mengulangi pada data.attributions.

<ScrollView style={styles.container}>
    {data.attributions.map(attr => <Text>{attr.something}</Text>}
</ScrollView>
0
HichamELBSI 4 Januari 2021, 14:41