You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中使用useEffect发起fetch请求出现无限循环问题求助

问题原因与解决方案

根本原因

  • 无限循环的核心问题是你没有给useEffect指定第二个依赖数组参数。React中useEffect如果不传依赖参数,会在每一次组件渲染完成后都重新执行:
    • useEffect内部调用了setCategories更新组件state,state更新会触发组件重新渲染
    • 重新渲染后又会触发useEffect执行,再次发起请求、更新state,由此形成无限循环

解决方法

给useEffect添加第二个参数,也就是空依赖数组[],这样useEffect只会在组件第一次挂载完成后执行一次,不会重复触发。
修正后的完整代码如下:

import { useState, useEffect } from 'react';

export function Category(){
    const [categories, setCategories] = useState([]);

    useEffect(() => {
        fetch('https://localhost:5001/api/Category')
        .then(response => response.json())
        .then(data => setCategories(data));
    }, []) // 此处添加空依赖数组,仅组件挂载时执行一次

    const renderCategories  = (cats) => {
        return (
        // 已同步修正小笔误:className小写、hoved改为hover、size去掉多余等号、map参数名避免重名
        <Table className= "mt-4" striped bordered hover size= "sm">
            <thead>
                <tr>
                    <th> Id: </th>
                    <th> Category Name: </th>
                    <th> Options </th>
                </tr>
            </thead>
            <tbody>
                {cats.map(cat=>
                    <tr key = {cat.categoryId}> 
                    <td> {cat.categoryId}</td>
                    <td> {cat.name}</td>
                </tr>)}                           
            </tbody>
        </Table>
        )
    }
    return(
        <div>
            {renderCategories(categories)}               
        </div>
    )    
}

补充说明

如果后续你的请求需要依赖某个变量(比如分类筛选参数、查询id等),把对应的变量放到依赖数组里即可,React会在该变量变化的时候才重新执行useEffect发起请求。

内容的提问来源于stack exchange,提问作者tobiasholmdk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 14:27:03