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

React函数式组件:更新percentageDone状态致非预期组件重渲染咨询

解决RenderData1Component不必要重渲染的问题

问题原因

父组件中percentageDone状态更新会触发父组件整体重渲染,即使RenderData1Component的props(data1)没有变化,默认情况下子组件也会跟着重渲染。

解决方案

1. 用React.memo包裹子组件

将RenderData1Component用React.memo包裹,让它仅在props发生浅变化时才重渲染:

import React, { memo } from 'react';

const RenderData1Component = memo(({ data }) => {
  // 组件原有逻辑代码
});

2. 确保loading状态的正确性

检查LoadDataFunction中loading的设置逻辑,保证加载过程中loading为true,避免提前渲染RenderData1Component:

  • 开始加载时立即设置setLoading(true)
  • 所有API请求完成后再设置setLoading(false)

调整后的LoadDataFunction示例:

const LoadDataFunction = async () => {
  setLoading(true);
  setPercentageDone(0);
  const apiTotal = 10;
  let completedNum = 0;

  const updateProgress = () => {
    completedNum++;
    setPercentageDone(Math.floor((completedNum / apiTotal) * 100));
  };

  // 批量发起API请求
  const apiTasks = Array.from({ length: apiTotal }, (_, idx) => 
    fetch(`/your-api-url/${idx}`)
      .then(res => res.json())
      .then(result => {
        // 处理单条接口返回数据
        updateProgress();
        return result;
      })
  );

  try {
    const allResults = await Promise.all(apiTasks);
    // 合并数据后更新data1状态
    setData1(allResults);
  } catch (error) {
    // 按需添加错误处理逻辑
  } finally {
    setLoading(false);
  }
};

3. 优化父组件的useEffect依赖

确保第二个useEffect中的condition是稳定值,避免无意义地重复触发LoadDataFunction。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 01:50:16