我是一名初学者,我决定做我的第一个项目-天气应用程序。尽管我有问题,但无法将解析的信息显示在屏幕上,但是如果我使用console.log,则信息将显示在控制台中。
我正在现场进行所有这些操作:https://snack.expo.io/
Copying you the codes and comment inside it console.logs
**CODE**
import React, { Component, createElement } from 'react';
import {
StyleSheet,
Text,
View,
Image,
ImageBackground,
ActivityIndicator,
} from 'react-native';
class App extends Component {
constructor(props) {
super(props);
this.state = {
todos: [],
isLoading: true,
};
}
componentDidMount = async () => {
fetch(
'https://api.openweathermap.org/data/2.5/weather?q=tbilisi,ge&units=metric&apikey=76dc3c2357c096b0f5e4ae5490f7f2bea'
)
.then(res => res.json())
.then(data => {
this.setState({ todos: data });
// console.log(data.coord.lon)
// console.log(data.coord.lat);
// console.log(data.weather[0].main);
// console.log(data.weather[0].description);
})
.catch(error => console.error(error))
.finally(() => {
this.setState({ isLoading: false });
});
};
render() {
const { data, isLoading } = this.state;
return (
<View>
<Text>
{data.weather[0].description}
</Text>
</View>
);
}
}
export default App;
谢谢!
不需要const {data,isLoading} = this.state,因为您已经在使用state和setState在您的示例中。
更改
this.state = {
todos: [],
isLoading: true,
};
到
this.state = {
todos: {},
isLoading: true,
};
尝试更改
<Text>
{data.weather[0].description}
</Text>
到
<Text>
{this.state.todos.weather[0].description}
</Text>
希望这会有所帮助!