【发布时间】:2020-06-05 03:29:36
【问题描述】:
这是基于本课程的练习 2.14 https://fullstackopen.com/en/part2/getting_data_from_server。
用户可以选择一个国家,然后显示该国家首都的天气信息。我的代码给了我错误无法读取未定义的属性“温度”
const Weather = ({ city }) => {
const [weatherDetails, setWeatherDetails] = useState([])
useEffect(() => {
axios.get('http://api.weatherstack.com/current', {
params: {
access_key: process.env.REACT_APP_WEATHER_KEY,
query: city
}
}).then(
(response) => {
setWeatherDetails(response.data)
}
)
}, [city])
console.log('weather', weatherDetails);
return (
<div>
<h3>Weather in {city} </h3>
{weatherDetails.current.temperature}
</div>
)}
基本上就是一行
{weatherDetails.current.temperature}
使我的代码崩溃。当我删除该行时,我可以通过 console.log 看到响应,但是有两个连续的日志
weather []
weather {request: {…}, location: {…}, current: {…}}
我认为我的代码发生在这两者之间,它甚至会在数据到达之前尝试访问数据,但我不知道如何解决这个问题。
另外,我不知道 useEffect() 的参数 [city] 是做什么的,所以如果有人可以向我解释它的作用,那就太好了。
编辑:已解决! 将weatherDetail的初始状态设置为null并进行了一些条件渲染
if (weatherDetails) {
return (
<div>
<h3>Weather in {capital}</h3>
{weatherDetails.current.temperature} Celsius
</div>
)
} else {
return (
<div>
Loading Weather...
</div>
)
}
【问题讨论】:
标签: reactjs axios react-hooks