【发布时间】:2020-08-20 20:35:02
【问题描述】:
我正在使用 React 制作一个基本的天气应用程序,但在让我的 setWeather 更新 weather 时遇到问题。我读过 setState 在第一次调用时不会更新状态,这似乎与 console.log(weather) 返回的空对象一致。 cityData 按预期返回完整响应,但 weather.name 和非嵌套数据(即只有字符串,而不是数组或对象)正常运行,这是出乎意料的。
我想知道如何让setWeather 像宣传的那样执行,以及为什么 API 返回的数组和对象显示为未定义。
import React, { useState } from 'react';
import axios from 'axios';
const Search = () => {
const [query, setQuery] = useState('');
const [weather, setWeather] = useState({});
const findCity = (e) => {
e.preventDefault()
axios.get(`https://api.openweathermap.org/data/2.5/weather?q=${query}&units=imperial&appid=${APIKEY}`)
.then(res => {
const cityData = res.data;
console.log(cityData);
setWeather(res.data);
setQuery('');
console.log(weather)
}).catch(err => console.log(err))
}
return(
<React.Fragment>
<h1>App</h1>
<p>Get the weather in your city!</p>
<form onSubmit={findCity}>
<input
type='text'
className='city-search'
placeholder='What city are you looking for?'
name='city-name'
onChange={e => setQuery(e.target.value)}
value={query}
/>
<button
type='submit'>
Get City
</button>
</form>
<h1>{weather.name}</h1>
</React.Fragment>
)
}
【问题讨论】:
标签: reactjs axios react-hooks