简体   繁体   English

componentDidMount 或 componentWillMount 在 React-Native 中不起作用?

[英]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.我正在尝试使用 API 获取城市,但 componentDidMount 和 componentWillMount 都在工作。

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...我已经使用按钮测试了我的 getWeather function,function 正在工作,但是当我尝试使用 componentDidMount 或 componentWillMount 调用它时它不起作用......

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


componentDidMount and componentWillMount only work in class based React components; componentDidMountcomponentWillMount仅适用于基于 class 的 React 组件; what you have here is a functional component.您在这里拥有的是一个功能组件。 You can use the useEffect hook to accomplish the same.您可以使用useEffect挂钩来完成相同的操作。

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

Note that this does not exist in functional components;请注意, this在功能组件中不存在; you can just call the function directly after you have declared it.您可以在声明后直接调用 function。

If you haven't used useEffect before, you may have questions about the array as the second argument.如果您之前没有使用useEffect ,您可能会对数组作为第二个参数有疑问。 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.如果要再次运行效果,请将依赖项添加到数组中。

ComponentDidMount would only work in class components. ComponentDidMount 仅适用于 class 组件。 Using the useEffect React hook would achieve the same effect without issues使用 useEffect React 钩子可以毫无问题地实现相同的效果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM