Can anyone tell me what I am doing wrong here. I am trying to fetch cities using API but componentDidMount nor componentWillMount is working.
I have tested my getWeather function using button, the function is working but when I try to call the it using componentDidMount or componentWillMount it is not working...
My code below:
import React, { Component } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import Header from './Header';
import { TextInput, Card, Button, Title } from 'react-native-paper';
import { useState } from 'react';
import { FlatList } from 'react-native-gesture-handler';
export default function Home() {
const [info, setInfo] = useState([{
city_name: "loading !!",
temp: "loading",
humidity: "loading",
desc: "loading",
icon: "loading"
}]);
getWeather = () => {
console.log("Hello Weather");
fetch("https://api.openweathermap.org/data/2.5/find?q=London&units=metric&appid={MY_API_KEY}")
.then(res => res.json())
.then(data => {
console.log(data);
/*setInfo([{
city_name: data.name,
temp: data.main.temp,
humidity: data.main.humidity,
desc: data.weather[0].description,
icon: data.weather[0].icon}]);
*/
})
}
componentWillMount = () => {
console.log("Hello Will");
this.getWeather();
}
componentDidMount = () => {
console.log("Hello Did");
this.getWeather();
}
return (
<View style={styles.container}>
<Header title="Current Weather"/>
<Card style = {{margin: 20}}>
<View>
<Title>{info.city_name}</Title>
<Title>{info.desc}</Title>
</View>
</Card>
<Button onPress={() => this.getWeather()} style={{margin: 40, padding: 20}}>Testing</Button>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…