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

React项目中如何为Chart.js的Bar柱状图动态添加数据集?

问题核心原因

  • 你错误地创建了全新的空Chart实例,这个实例和页面上渲染的react-chartjs-2的Bar组件没有任何关联,调用它的update方法自然不会生效
  • data和options定义在组件外部属于普通变量,没有用React状态管理,修改后React不会触发组件重渲染,图表无法感知数据变化
  • 存在多处配置语法错误:
    1. Chart.js V3+版本的Y轴配置字段是scales.y,不是旧版本的YAxes数组
    2. beginAtZero是布尔类型配置,只能传true/false,不能传入数值8
    3. responsive是全局配置项,需要放在options中,不能写在单个dataset里

修正后的完整代码

import { useState } from 'react';
import { Bar } from 'react-chartjs-2';
import { Chart as ChartJS, CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend } from 'chart.js';

// 注册Chart.js必要组件,避免渲染报错
ChartJS.register(CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend);

const Dashboard = (props) => {
  // 用useState管理图表数据,修改后自动触发重渲染
  const [data, setData] = useState({
    labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
    datasets: [
      {
        label: 'Statistics',
        data: [4, 10, 7, 1, 8, 9],
        backgroundColor: [
          'rgba(255, 99, 132, 0.2)',
          'rgba(54, 162, 235, 0.2)',
          'rgba(255, 206, 86, 0.2)',
          'rgba(75, 192, 192, 0.2)',
          'rgba(153, 102, 255, 0.2)',
          'rgba(255, 159, 64, 0.2)',
        ],
        borderColor: [
          'rgba(255, 99, 132, 1)',
          'rgba(54, 162, 235, 1)',
          'rgba(255, 206, 86, 1)',
          'rgba(75, 192, 192, 1)',
          'rgba(153, 102, 255, 1)',
          'rgba(255, 159, 64, 1)',
        ],
        borderWidth: 4,
      },
    ],
  });

  const options = {
    responsive: true,
    scales: {
      y: {
        ticks: {
          beginAtZero: true,
        },
      },
    },
  };

  const addDatasets = () => {
    const newDataset = {
      label: "Statistics of activity",
      data: [8, 10, 9, 17, 25, 31],
      backgroundColor: 'rgba(255, 0, 0, 0.2)',
      borderColor: 'rgba(0, 0, 255, 1)',
      borderWidth: 4,
    };
    // 更新state触发重渲染,react-chartjs-2会自动更新图表
    setData(prev => ({
      ...prev,
      datasets: [...prev.datasets, newDataset]
    }));
  };

  return (
    <>
      <div className='header'>
        <h1 className='title'>Vertical Bar Chart</h1>
        <div className='links'>
          <a
            className='btn btn-gh'
            href='https://github.com/reactchartjs/react-chartjs-2/blob/master/example/src/charts/VerticalBar.js'
          >
            Github Source
          </a>
        </div>
      </div>
      <Bar data={data} options={options}  />
      <button onClick={addDatasets}>Add Datasets</button>
    </>
  );
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 05:09:02