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

如何将BillingSummaryDTO数组数据渲染为Recharts柱状图

实现方案

你只需要完成接口请求、DTO数据格式转换、替换图表数据源三个步骤即可,完整修改后的代码如下:

第一步:补全依赖导入

首先在文件头部补充需要的 hooks、工具和接口导入:

import { useState, useEffect } from 'react';
import moment from 'moment';
import { getBillingSummary, BillingSummaryDTO } from '你的接口文件实际路径';
// 原有recharts、material-ui的导入保持不变

第二步:定义图表数据类型、修改组件逻辑

把原有Billing组件替换为以下内容:

// 定义转换后的图表数据类型
type ChartDataType = {
  name: string;
  已支付: number;
  未结清: number;
  逾期: number;
  已取消: number;
}

export default function Billing() {
  const [click, setClick] = useState(false);
  const closeMobileMenu = () => setClick(false);
  const classes = useStyles();
  const classesPaper = usePaperStyles();
  const classesTimeline = useTimelineStyles();
  // 新增:图表数据、加载状态定义
  const [chartData, setChartData] = useState<ChartDataType[]>([]);
  const [loading, setLoading] = useState(false);

  // 新增:组件挂载时请求接口并转换数据
  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      try {
        const res = await getBillingSummary();
        const dtoList = res.data;
        // DTO转图表兼容格式
        const transformed = dtoList.map((dto: BillingSummaryDTO) => {
          // 过滤掉创建时间为空的无效数据
          if (!dto.createdAt) return null;
          return {
            // 把日期格式化为月份缩写,需要中文月份可改为dto.createdAt.format('M月')
            name: dto.createdAt.format('MMM'),
            已支付: dto.paid ?? 0,
            未结清: dto.outstanding ?? 0,
            逾期: dto.pastDue ?? 0,
            已取消: dto.cancelled ?? 0,
          }
        }).filter(Boolean) as ChartDataType[];
        setChartData(transformed);
      } catch (err) {
        console.error('账单数据获取失败', err);
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, []);

  return (
    <>
      <Grid container justifyContent="center" alignItems="center">
        <Grid item xs={11}>
          {/*Padding on the top*/}
          <Box m="5rem" />
        </Grid>

        <Grid item xs={12} >
          <h4 className="chart-label">Invoices Summary</h4>
          {/* 把原有固定data替换为转换后的chartData,可加loading判断 */}
          {loading ? <p>数据加载中...</p> : (
            <BarChart
              width={1000}
              height={300}
              data={chartData}
              margin={{
                top: 5,
                right: 30,
                left: 20,
                bottom: 5,
              }}
              barSize={30}
            >
              <XAxis
                dataKey="name"
                scale="point"
                padding={{ left: 10, right: 10 }}
              />
              <YAxis />
              <Tooltip />
              <Legend />
              <CartesianGrid strokeDasharray="3 3" />
              {/* 需要展示哪个字段就加对应的Bar组件,自定义颜色即可 */}
              <Bar dataKey="已支付" fill="#4CAF50" background={{ fill: "#eee" }} />
              <Bar dataKey="未结清" fill="#FF9800" background={{ fill: "#eee" }} />
              <Bar dataKey="逾期" fill="#F44336" background={{ fill: "#eee" }} />
              <Bar dataKey="已取消" fill="#9E9E9E" background={{ fill: "#eee" }} />
            </BarChart>
          )}
        </Grid>
      </Grid>
    </>
  );
}

自定义调整说明

  • 如果只需要展示单个指标,删除多余的Bar组件即可
  • 如果需要堆叠柱状图,给所有Bar组件加上相同的stackId属性即可
  • 月份显示格式可以通过调整moment.format()的参数自定义

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 23:24:02