使用 useEffect 的无限获取循环问题

Issue with infite fetch loop using useEffect

我在 useEffect() 中获取数据时遇到问题。 我可以在开发人员工具中看到,提取是在无限循环中调用的。

我对 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>
    )    
}

useEffectstate 发生变化时被调用。在您的代码中,您在 useEffect 中调用 setCategories 来更改 categories 状态。该操作会在无限循环中触发 useEffect 本身。

这是使用 hooks 学习 React 17 的新人甚至前 React Class 开发人员的常见问题。为避免这种情况,使用方括号 [] 像 @Chris G 目前是可以的,但在缩放时这不是一个好的做法,因为你只是 tricks React to runs useEffect一次。

Dan Abramov 建议使用 useReducer 来管理 useEffect 之外的状态。 这是他的优秀文章,解释了useEffect的每个角落。我们倒点咖啡来读吧,因为它和一本书一样长:https://overreacted.io/a-complete-guide-to-useeffect/