【发布时间】:2020-06-25 01:33:08
【问题描述】:
我正在使用 axios 通过 useEffect 获取天气 api 数据。
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { Header } from './Header';
export const CurrentCity = () => {
const [weather, setWeather] = useState({});
console.log('weather', weather);
console.log(weather.weather[0].icon);
useEffect(() => {
async function getData() {
const url = `https://api.openweathermap.org/data/2.5/weather?q=Berlin&appid=${process.env.REACT_APP_WEATHER_KEY}`;
try {
const response = await axios.get(url);
setWeather(response.data);
} catch (err) {
console.log(err);
}
}
getData();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<div>
<Header api={weather} />
</div>
);
};
这是 console.log(data) 的结果:
{coord: {…}, weather: Array(1), base: "stations", main: {…}, visibility: 10000, …}
coord: {lon: 13.41, lat: 52.52}
weather: Array(1)
0: {id: 802, main: "Clouds", description: "scattered clouds", icon: "03n"}
length: 1
__proto__: Array(0)
base: "stations"
main: {temp: 278.43, feels_like: 270.3, temp_min: 276.48, temp_max: 280.37, pressure: 1009, …}
visibility: 10000
wind: {speed: 8.7, deg: 270, gust: 13.9}
clouds: {all: 40}
dt: 1584060559
sys: {type: 1, id: 1275, country: "DE", sunrise: 1584077086, sunset: 1584119213}
timezone: 3600
id: 2950159
name: "Berlin"
cod: 200
__proto__: Object
如果我控制台记录我得到的数据
console.log('weather', weather);
console.log(weather.weather[0].icon);
错误信息说,它无法读取[0]的属性,
或者如果我尝试更深入地了解“风”,例如,
console.log(weather.wind.speed);
它说,无法读取速度的属性。
如果它是我想要访问的数组,我会使用 [0] 或者如果它是一个对象,我会使用点符号。
此外,我将从 axios 获得的数据传递给 Header.js
import React from 'react';
export const Header = props => {
console.log(props.api.name);
return (
<div>
<h1>{props.api.name}</h1>
</div>
);
};
当我尝试深入研究其他数据时,也会发生同样的情况。
我想知道我缺少什么,提前谢谢大家! 并且还想知道 1 和 2 之间有什么区别,我应该在当前情况下使用哪一个。
const [weather, setWeather] = useState({});const [weather, setWeather] = useState(null);
【问题讨论】:
-
当你调用
console.log(weather.weather[0].icon);时,天气只是初始化为{},所以你会在控制台看到错误信息。 -
1和2的区别是
weather在第1个初始化为{},在第2个初始化为null -
@JongHyeokLee 另见stackoverflow.com/help/someone-answers
标签: javascript reactjs axios use-effect