【发布时间】:2022-01-28 07:40:06
【问题描述】:
目前,我只能在加载国家名称时提取信息,我添加代码,保存它,然后在 localhost 上更新。但是当我在另一个国家/地区输入时,我收到了Uncaught TypeError: Cannot read properties of undefined (reading 'temp') 的错误。例如,我的代码 {weather.main.temp} 有效,但前提是之前已经设置了 state = "france"。
我的子组件:
const WeatherInfo = ({ country }) => {
const [weather, setWeather] = useState({});
useEffect(() => {
axios
.get(`https://api.openweathermap.org/data/2.5/weather?q=${country.capital}&appid=${api_key}&units=imperial`)
.then(response => {
console.log(response.data)
setWeather(response.data)
})
}, [country])
return (
<div>
<h3>Weather in {country.capital}</h3>
<p><b>Temperature</b>{weather.main.temp}</p>
</div>
)
}
【问题讨论】:
标签: javascript reactjs axios