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

React.js饼图显示空白:计算百分比后无法正常渲染

问题分析与修复方案

1. 百分比计算逻辑错误(核心问题)

你的百分比计算方式会导致数据总和远大于100%,甚至出现Infinity(当分母为0时),Chart.js无法处理这类无效数据,直接导致饼图空白。

错误计算示例:
若totalExpected=100,totalCollected=50,则:

  • expectedPercentage = (100/50)*100 = 200%
  • collectedPercentage = (50/100)*100 = 50%
    总和250%,完全不符合饼图的比例逻辑。

修正后的计算逻辑:
以两者总和为基数,计算各自占比(确保总和为100%):

const total = totalExpected + totalCollected;
const expectedPercentage = total > 0 ? (totalExpected / total) * 100 : 0;
const collectedPercentage = total > 0 ? (totalCollected / total) * 100 : 0;

如果你的需求是展示「已收集量占预期量的比例」(而非两者总量占比),则饼图应该分为「已收集」和「未完成」两部分,计算逻辑调整为:

const collectedPercentage = totalExpected > 0 ? (totalCollected / totalExpected) * 100 : 0;
const remainingPercentage = totalExpected > 0 ? 100 - collectedPercentage : 0;
// 同时将PieChart的props改为collectedPercentage和remainingPercentage,labels对应调整为['Collected', 'Remaining']

2. 饼图容器缺少高度设置

react-chartjs-2的Pie组件依赖父容器的明确尺寸,没有高度会导致渲染空白。

添加容器样式:
在CSS中设置容器尺寸:

.pie-chart-container {
  height: 300px;
  width: 300px;
}

3. 完善Chart.js注册项(可选)

虽然你已经注册了ArcElement,但添加Tooltip和Legend可以提升交互体验,避免潜在的渲染问题:

// 在PieChart组件中修改导入和注册
import { Chart, ArcElement, Tooltip, Legend } from 'chart.js';
Chart.register(ArcElement, Tooltip, Legend);

最终修正后的完整代码

父组件中的计算与调用

// 修正百分比计算
const total = totalExpected + totalCollected;
const expectedPercentage = total > 0 ? (totalExpected / total) * 100 : 0;
const collectedPercentage = total > 0 ? (totalCollected / total) * 100 : 0;

// 组件调用
<PieChart className='pie-chart-container'
  expectedPercentage={expectedPercentage}
  collectedPercentage={collectedPercentage}
/>

PieChart组件

import React from 'react';
import { Pie } from 'react-chartjs-2';
import { Chart, ArcElement, Tooltip, Legend } from 'chart.js';

// 注册必要的Chart.js元素
Chart.register(ArcElement, Tooltip, Legend);

const PieChart = ({ expectedPercentage, collectedPercentage }) => {
  const data = {
    labels: ['Expected', 'Collected'],
    datasets: [
      {
        data: [expectedPercentage, collectedPercentage],
        backgroundColor: ['#FF6384', '#36A2EB']
      }
    ]
  };
  return <Pie data={data} />;
};

export default PieChart;

CSS样式

.pie-chart-container {
  height: 300px;
  width: 300px;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 22:35:30