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

React报错Too many re-renders排查与部门数据统计实现

解决React无限重渲染问题并实现部门统计需求

报错信息

react-dom.development.js:16317 Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop

现有代码

let [depart, setdepartment] = useState({
        Frontend: 0,
        Backend: 0,
        Testing: 0,
        Deployment: 0,
    });
    Object.keys(localStorage).forEach(function (key, value) {
        let temp = JSON.parse(localStorage.getItem(key));
        setdepartment(prev => ({
            ...prev,
            [temp.department]: depart.Frontend.value +1,
        }));
    });

需求说明

当localStorage中的数据对象包含Frontend、Backend、Testing、Deployment部门时,对应部门的数值加1,期望最终状态为:

let [depart, setdepartment] = useState({
        Frontend: 3,
        Backend: 1,
        Testing: 1,
        Deployment: 2,
    });

问题排查与修复

无限重渲染原因

  1. 直接在组件渲染阶段调用setdepartment:每次状态更新都会触发组件重新渲染,渲染时又会重复执行这段循环更新状态的代码,形成无限循环。
  2. 数值更新逻辑错误:代码中错误引用depart.Frontend.value(depart.Frontend本身就是数值,不存在value属性),且没有基于对应部门的当前状态值累加。

修复代码

import { useState, useEffect } from 'react';

function YourComponent() {
    const [depart, setDepartment] = useState({
        Frontend: 0,
        Backend: 0,
        Testing: 0,
        Deployment: 0,
    });

    useEffect(() => {
        // 初始化统计对象,复制初始状态结构
        const departmentCount = { ...depart };
        
        // 遍历localStorage统计各部门数量
        Object.keys(localStorage).forEach(key => {
            const item = JSON.parse(localStorage.getItem(key));
            // 校验部门是否在统计范围内,避免无效数据
            if (departmentCount.hasOwnProperty(item.department)) {
                departmentCount[item.department] += 1;
            }
        });
        
        // 一次性更新状态,仅触发一次渲染
        setDepartment(departmentCount);
    }, []); // 空依赖数组确保仅在组件挂载时执行一次

    return (
        // 组件渲染内容
    );
}

代码说明

  1. useEffect控制执行时机:空依赖数组[]让统计逻辑只在组件首次挂载时运行一次,彻底避免重复触发渲染。
  2. 批量统计后更新:先遍历完成所有部门的数量统计,再调用一次状态更新函数,减少渲染次数。
  3. 数据有效性校验:通过hasOwnProperty检查过滤掉localStorage中不属于目标范围的部门数据,避免出现异常值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 17:40:46