使用 React Native 调用开放天气 API

Call Open Weather API with React Native

我正在试验开放天气。我试图用温度数字替换 Text 元素的 innerHTML。如果我提醒常量温度,我会不确定....

import React, { Component } from 'react';
import { StyleSheet, Button, Alert, Text, View, ImageBackground, TextInput} from 'react-native';
const openweather_api = "https://api.openweathermap.org/data/2.5/weather?q=V&appid=somenumberss&units=metric";

export default class App extends Component {
  state = {};

  componentDidMount(){
    async function getWeather() {
      try {
        const response = await fetch(openweather_api);  
        const json = await response.json();
        console.log(json) // works, it returns the weather data..
        alert(json.main.temp) // works, it returns 2 degrees. 
        this.setState({
          temperature: json.main.temp,
          humidity: json.main.humidity,
        });
        } catch (e) {
        alert('something went wrong')
        }
      }
    getWeather();
  }

  render() {
alert(json.main.temp) // gets undefined.. 
console.log(this.state) // returns {} __proto__.....

  return (
  <View style={styles.container}>
     <Text>Today's temperature is {this.state.temperature} Celcius</Text>
    <Text>{this.state.humidity > 100 && this.state.temperature > 20 ? 'nice weather' : 'bad weather'}</Text>
    </View>
  );
}

}

将其发展成答案。 正常的工作流程是这样的:

export default class App extends Component {
  state = {
    temperature: 0,
    humidity: 0,
  };

componentDidMount() {
  this.getWeather();
}

function getWeather() {
      fetch(openweather_api).then(res => res.json)
      .then((data) => {
        console.log('data', data)
        this.setState({
          temperature: data.main.temp,
          humidity: data.main.humidity,
        });
    }

render(){
    return(
        <View style={styles.weather}>
          <Text>Today's temperature is {this.state.temperature} Celcius</Text>
          <Text>{this.state.humidity > 100 && this.state.temperature > 20 ? 'It's nice outside, go for a run!' : 'It's too cold to run outside'}</Text>
        </View>
}

然后您在 componentDidMount 中调用您的函数。

当然它并不完美,但你明白了。希望这对您有所帮助!