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

时间:2021-01-06 16:54:57

标签: javascript reactjs react-native api

谁能告诉我我在这里做错了什么。我正在尝试使用 API 获取城市,但 componentDidMount 和 componentWillMount 都在工作。

我已经使用按钮测试了我的 getWeather 函数,该函数正在运行,但是当我尝试使用 componentDidMount 或 componentWillMount 调用它时,它不起作用......

我的代码如下:

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


2 个答案:

答案 0 :(得分:1)

componentDidMountcomponentWillMount 仅适用于基于类的 React 组件;您在这里拥有的是一个功能组件。您可以使用 useEffect 钩子来完成相同的操作。

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

注意 this 不存在于函数组件中;您可以在声明后直接调用该函数。

如果您之前没有使用过 useEffect,您可能对数组作为第二个参数有疑问。如果它为空,它将在 mount 上运行,并将运行您从 unmount 时的第一个参数返回的内容。如果您想再次运行您的效果,请在数组中添加一个依赖项。

答案 1 :(得分:0)

ComponentDidMount 只能在类组件中工作。使用 useEffect React hook 可以毫无问题地达到相同的效果

相关问题