【发布时间】:2021-12-31 09:33:35
【问题描述】:
所以我遇到了这个问题。我正在使用 axios 获取数据并希望将其分配给 useState。但是,包括 useEffect 中的 async 函数在内的所有方法都没有这样做。所以第一个 console.log(res.data) 很好地显示了所有信息。但是,第二个 console.log(weather) 显示一个空数组。有什么建议吗?
const App = () => {
const [weather, setWeather] = useState([]);
const [loading, setLoading] = useState(true);
// Side effects
useEffect(() => {
axios
.get("https://weather-app-tst.herokuapp.com/api/weather")
.then((res) => {
setLoading(false);
console.log(res.data);
setWeather(res.data);
console.log(weather);
})
.catch((error) => console.log(error))
}, []);
【问题讨论】:
标签: javascript reactjs react-hooks