我正在使用axios从我的react应用程序的openweathermap API中获取天气信息,从api调用的结果(一个json对象)中,我可以访问一些属性,例如data.base
,但是不能访问data.coord.icon
或data.weather[0].id
等。
data = [
coord: { lon: -0.1257,lat: 51.5085},
weather: [{ id: 721,
main: "Haze",
description: "haze",
icon: "50n"
}],
base: "stations"
]
我尝试了所有可能的组合。当尝试返回data.coord
时,得到错误对象作为React子对象无效(发现:如果您想要呈现子对象的集合,请改用数组但是data.coord.lon
给出了lon of undefined
import React, { Component } from 'react';
import axios from 'axios';
export class WeatherInfo extends Component {
constructor(props) {
super(props)
this.state = {
isFetching: false,
data: [],
}
}
//function to fetch weather information
async getWeatherData(lat, lon) {
const weatherApi = `http://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${process.env.REACT_APP_WEATHER_KEY}`
try {
this.setState({ ...this.state, isFetching: true });
const response = await axios.get(weatherApi);
this.setState({ data: response.data, isFetching: false });
console.log(response.data)
} catch (error) {
console.log(error);
this.setState({ isFetching: false })
}
}
//function to get access to users location and to call getWeatherData function
weatherInit = () => {
const success = (position) => {
this.getWeatherData(position.coords.latitude, position.coords.longitude);
}
const error = () => {
alert('Unable to retrieve location.');
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
alert('Your browser does not support location tracking, or permission is denied.');
}
}
componentDidMount() {
this.weatherInit();
}
render() {
const { data } = this.state;
return (
<div>
<p>{data.name}</p>
</div>
)
}
}
export default WeatherInfo
1条答案
按热度按时间dced5bon1#
下面是如何显示API返回的各种数据的示例。
您必须为每个要显示的值创建一个JSX元素。抱歉,这是为了格式化。