Jac*_*cob 2 reactjs react-hooks
我正在构建一个小项目来更熟悉 Hooks,但我现在遇到了一个问题:
该项目是一个天气应用程序,从 API 中提取城市的天气数据。下面的代码是该应用程序的简化版本。\
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
)
}
Run Code Online (Sandbox Code Playgroud)
预期行为:
单击li元素将状态设置city为新城市并重新渲染 UI,加载所选城市的天气数据。
实际行为: 状态已设置,但应用程序不会重新加载数据。
您需要指定city为依赖项,告诉何时重新执行效果。
有关参数的更多详细信息,请参阅有条件地触发效果[]。
useEffect(() => {
axios.get(`https://api-url/?query=${city}`)
.then(res => setWeather(res.data))
.catch ...
}, [city])
Run Code Online (Sandbox Code Playgroud)
另请参阅ESLint 插件以了解 Hooks 和 Exhaustive Deps 的规则。
| 归档时间: |
|
| 查看次数: |
2337 次 |
| 最近记录: |