Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

javascript - componentDidMount or componentWillMount not working in React-Native?

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


question from:https://stackoverflow.com/questions/65599975/componentdidmount-or-componentwillmount-not-working-in-react-native

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

componentDidMount and componentWillMount only work in class based React components; what you have here is a functional component. You can use the useEffect hook to accomplish the same.

useEffect(() => {
  getWeather();
}, []);

Note that this does not exist in functional components; you can just call the function directly after you have declared it.

If you haven't used useEffect before, you may have questions about the array as the second argument. If it is empty, it will run on mount and will run what you return from the first argument on unmount. If you want to run your effect again, add an dependencies into the array.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...