【发布时间】:2021-11-22 02:04:41
【问题描述】:
我在使用 useEffect() 中获取数据时遇到问题。 我可以在开发者工具中看到,fetch 是在无限循环中调用的。
我对 React 很陌生,所以也许这是一个简单的问题。我曾尝试查找其他有相同问题的人,但似乎无法与我的代码建立联系。
代码如下。
export function Category(){
const [categories, setCategories] = useState([]);
useEffect(() => {
fetch('https://localhost:5001/api/Category')
.then(response => response.json())
.then(data =>
setCategories(data));
return () => {
}
})
const renderCategories = (cats) => {
return (
<Table ClassName= "mt-4" striped bordered hoved size= "=sm">
<thead>
<tr>
<th> Id: </th>
<th> Category Name: </th>
<th> Options </th>
</tr>
</thead>
<tbody>
{cats.map(cats=>
<tr key = {cats.categoryId}>
<td> {cats.categoryId}</td>
<td> {cats.name}</td>
</tr>)}
</tbody>
</Table>
)
}
return(
<div>
{renderCategories(categories)}
</div>
)
}
【问题讨论】:
-
useEffect 块的最后一行,
}),必须是}, [])(即一个空的依赖数组将确保函数只运行一次,而不是每次状态改变时) -
请阅读 useEffect 文档
-
useEffect 在每次渲染时被调用(除非你使用一个空的依赖数组)并且 setState 会触发一个重新渲染,导致你的无限循环。
标签: javascript reactjs react-hooks use-effect