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

React项目中useEffect触发无限循环的原因与解决方法

无限循环成因及解决方案

成因分析

  1. 循环内频繁触发状态更新:在useEffect的map遍历逻辑中,每处理一条数据就调用一次setxytotalTopography/setXTopography/setxyAge,每次状态更新都会触发组件重新渲染,进而再次执行useEffect,形成闭环循环。
  2. 直接修改外部可变数组并复用引用:xytTopography、topography、ageBar是组件每次渲染都会重新声明的数组,在useEffect中直接push修改后将原引用传给setState。一方面React依赖引用变化判断状态更新,原引用复用可能导致更新异常;另一方面组件重新渲染时这些数组会被重新初始化,再次触发useEffect重复处理。
  3. 依赖了完整的React Query对象:chartsQueryTopographyData和chartsQueryAgeData是React Query返回的完整查询对象,包含isLoading、status等多个属性,任何属性变化都会触发useEffect重新执行,即使接口数据已经稳定。

修复方案

  1. 在useEffect内部创建新数组,一次性更新状态:先完成所有数据的处理逻辑,再统一调用setState,避免循环内频繁触发渲染。
  2. 仅监听query的data属性作为依赖:React Query的data只有在接口返回新数据时才会变化,比监听整个query对象更精准,减少不必要的useEffect执行。
  3. 移除组件级可变数组变量:将数据处理的临时数组移到useEffect内部,避免每次渲染重新初始化带来的干扰。

修复后的BarChart.tsx关键代码

const BarCharts: FunctionComponent<BarChartsProps> = () => {
    const today = new Date();
    const year = today.getFullYear();

    // 只解构出data属性,避免依赖整个query对象
    const { data: topographyData } = useQuery(['chartsQueryTopographyData'], () =>
        statisticCharts.GetTopographyStatistic({ FilterType: 1, StartDate: `${year}-01-01`, EndDate: `${year}-12-31` }),
    );

    const { data: ageData } = useQuery(['chartsQueryAgeData'], () =>
        statisticCharts.GetTopographyStatistic({ FilterType: 3, StartDate: `${year}-01-01`, EndDate: `${year}-12-31` }),
    );

    // 初始化状态为默认表头
    const [xytotalTopography, setxytotalTopography] = useState<any[]>([['topography', 'ذكر', 'أنثى']])
    const [xtopography, setXTopography] = useState<any[]>([['topography', 'المرضى المصابين']]);
    const [xyAge, setxyAge] = useState<any[]>([['age', 'المرضى المصابين']])

    useEffect(() => {
        if (!topographyData) return;

        // 处理性别分类数据,创建新数组避免修改外部变量
        const newXytTopography = [['topography', 'ذكر', 'أنثى']];
        topographyData.forEach((xy: any) => {
            if (xy?.x !== undefined && xy?.yMale !== undefined && xy?.yFemale !== undefined) {
                newXytTopography.push([xy.x, xy.yMale, xy.yFemale]);
            }
        });
        setxytotalTopography(newXytTopography);

        // 处理病例总数数据
        const newTopography = [['topography', 'المرضى المصابين']];
        topographyData.forEach((xy: any) => {
            if (xy?.x !== undefined && xy?.yTotal !== undefined) {
                newTopography.push([xy.x, xy.yTotal]);
            }
        });
        setXTopography(newTopography);

    }, [topographyData]); // 仅依赖data属性

    useEffect(() => {
        if (!ageData) return;

        // 处理年龄分类数据
        const newAgeBar = [['age', 'المرضى المصابين']];
        ageData.forEach((xy: any) => {
            if (xy?.x !== undefined && xy?.yTotal !== undefined) {
                newAgeBar.push([xy.x, xy.yTotal]);
            }
        });
        setxyAge(newAgeBar);

    }, [ageData]); // 仅依赖data属性

    // 原有return部分保持不变
}

额外优化建议

可以直接使用useMemo在渲染时转换数据,无需额外维护状态,进一步简化代码并避免状态更新带来的渲染问题:

// 示例:用useMemo直接处理性别分类数据
const xytotalTopography = useMemo(() => {
    if (!topographyData) return [['topography', 'ذكر', 'أنثى']];
    return topographyData.reduce((acc, xy) => {
        if (xy?.x !== undefined && xy?.yMale !== undefined && xy?.yFemale !== undefined) {
            acc.push([xy.x, xy.yMale, xy.yFemale]);
        }
        return acc;
    }, [['topography', 'ذكر', 'أنثى']] as any[]);
}, [topographyData]);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 01:28:12