使用React Native调用Open Weather API

问题描述 投票:0回答:1

我正在尝试开放天气。我试图用温度编号将innerHTML替换为Child组件。如果我在getWeather()中警告const tempaturatur,它将起作用,但在渲染中不起作用。

openweather_api = "https://api.openweathermap.org/data/2.5/weather?q=city&appid=anonym&units=metric";

      async function getWeather() {
          const response = await fetch(openweather_api);  
          const json = await response.json();
          const temperature = `${json.main.temp}`

          alert(temperature) // works fine...

          if( `${json.main.humidity}` > 100 && `${json.main.temp}` > 20){
          let weather = 'It's nice outside, go for a run!'

          }
          else if(`${json.main.humidity}` < 100 && `${json.main.temp}` < 10 ) {
              let weather = 'It's too cold to run outside' 
          }
      }

getWeather();

export default class Weather extends Component {

    render(){

        alert(temperature) // not working
        return(
            <View style={styles.weather}>
            <Text>Today's temperature is {temperature} Celcius</Text>
            <Text>{weather}</Text>
            <Text></Text>
            </View>)}
}
react-native weather-api
1个回答
0
投票

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

async function getWeather() {
      const response = await fetch(openweather_api);  
      const json = await response.json();
      if (json.main) {
      this.setState({
        temperature: json.main.temp,
        humidity: json.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中调用函数。

当然,这并不完美,但您会明白的。希望这会有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.