【发布时间】:2021-04-14 11:37:46
【问题描述】:
我正在使用 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 时,得到错误 Objects are not valid as a React child (found: object with keys {lon, lat})。如果您打算渲染一组子项,请改用数组
但是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
【问题讨论】:
-
你能不能
console.log(response.data)你得到并在这里显示输出。 -
显示一些代码。
-
需要更多的上下文才能知道你在说什么。
-
@NikitaGalibin coord: {lon: 76.2711, lat: 10.8505} weather: [{…}] base: "stations" main: {temp: 297.15, feel_like: 301.07, temp_min: 297.15, temp_max: 297.15,压力:1008,...} 能见度:1500 风:{速度:1.03,度:70} 云:{全部:75} dt:1610131334 系统:{类型:1,id:9209,国家:“IN”,日出:1610154958,日落:1610196454} 时区:19800 id:1256432 名称:“Shōranūr” 编码:200
-
你想在哪里显示它?如果可能,请提供整个组件的代码。
标签: javascript json reactjs object openweathermap