react-native - 使用 React Native 调用 Open Weather API
问题描述
我正在尝试开放天气。我试图用温度数字替换 Text 元素的 innerHTML。如果我提醒 const 温度,我会变得不确定....
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
。
当然它并不完美,但你明白了。希望这可以帮助!
推荐阅读
- maven - 为什么我的班级找不到“ContractVerifierUtil”?
- javascript - 如何重组/翻译 Json 对象以满足任何模式?
- c# - 为什么使用泛型类型进行强制转换不起作用?
- java - Intellij 生成静态最终字段
- ios - 为什么我不能直接设置视图底层图层的背景颜色?
- typedef - 使用 typedef + 压缩数组(与多维压缩数组相比)的每个元素的有符号类型是否有效
- c# - T 是枚举成员的接口。这是糟糕的设计吗?
- rm - 如何递归删除目录中除特定文件类型和文件夹之外的所有文件?
- c++ - 如何在运行时优雅地排除代码块
- html - 浮动:左高度设置为0px