[英]useEffect not re-rendering after state change
I am building a little side project to get more familiar with Hooks and I am running into a problem right now: 我正在建立一个小项目,以更熟悉Hooks,现在遇到了一个问题:
The project is a weather app, pulling weather data for a city from an API. 该项目是一个天气应用程序,可从API中提取城市的天气数据。 The code below is a simplified version of the app.
下面的代码是该应用程序的简化版本。 \\
\\
import React, { useState, useEffect } from "react"
import axios from "axios"
const App: React.FC = () => {
const [weather, setWeather] = useState<any>({})
const [city, setCity] = useState<string>("London")
const [cities, setCities] = useState<string[]>([
"London",
"New York",
"Dubai",
"Berlin",
"Los Angeles",
"Sydney",
])
useEffect(() => {
axios.get(`https://api-url/?query=${city}`)
.then(res => setWeather(res.data))
.catch ...
}, [])
return (
<Drawer>
<nav>
<ul>
{cities.map((c, i) => (
<li key={i} onClick={() => setCity(c)}>
{c}
</li>
))}
</ul>
</nav>
</Drawer>
// more JSX to display weather data for current city
)
}
Expected behaviour: Clicking on li
elements sets the state of city
to the new city and rerenders the UI, loading the weather data for the selected city. 预期的行为:点击
li
元素设置的状态, city
新城区和重新渲染UI,加载天气数据选定的城市。
Actual behavour: State gets set, but app doesn't reload the data. 实际行为:状态已设置,但应用程序不会重新加载数据。
You need to specify city
as the dependency, telling when to re-execute the effect. 您需要指定
city
作为依赖项,告诉何时重新执行效果。
See Conditionally firing an effect for more details about the []
argument. 有关
[]
参数的更多详细信息,请参见有条件地触发效果 。
useEffect(() => {
axios.get(`https://api-url/?query=${city}`)
.then(res => setWeather(res.data))
.catch ...
}, [city])
Also see ESLint plugin for Rules of Hooks and Exhaustive Deps. 另请参阅ESLint插件,以了解挂钩规则和详尽的Deps。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.