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

React结合ChartJS实现流式实时折线图无法动态更新问题求助

你安装的依赖无问题,不需要额外嵌入HTML资源,无法实现动态滚动是配置语法与React更新逻辑的问题,修复方案如下:

核心问题

  • 使用了Chart.js v3+版本,但scale配置仍沿用v2的xAxes/yAxes数组写法,版本语法不兼容
  • 直接修改定义的普通变量不会触发React组件重渲染,Chart组件接收的props无更新,看不到动态效果
  • 缺少realtime.duration参数配置,该参数定义X轴显示的时间窗口长度,是滚动效果的必需配置
  • Y轴的标题配置字段在v3版本中已从scaleLabel改为title,原有配置不生效

修复后完整代码

import React, { useState } from "react";
import { Line } from "react-chartjs-2";
import Chart from "chart.js/auto";
import { StreamingPlugin, RealTimeScale } from "chartjs-plugin-streaming";
Chart.register(StreamingPlugin, RealTimeScale);

export const IotChart = () => {
  // 用useState管理数据,保证修改后触发组件重渲染
  const [data, setData] = useState({
    datasets: [
      {
        label: "Dataset 1",
        fill: false,
        lineTension: 0.4,
        backgroundColor: "#f44336",
        borderColor: "#f44336",
        borderJoinStyle: "miter",
        pointRadius: 0,
        showLine: true,
        data: [],
      },
    ],
  });

  const options = {
    responsive: true,
    scales: {
      // Chart.js v3+ X轴配置写法
      x: {
        type: "realtime",
        realtime: {
          // 配置X轴显示最近10秒的数据,可按需调整数值
          duration: 10000,
          onRefresh: () => {
            const newDataset = [...data.datasets];
            newDataset[0].data.push({
              x: Date.now(),
              y: Math.random() * 100,
            });
            setData({
              ...data,
              datasets: newDataset
            });
          },
          delay: 300,
          refresh: 300,
        },
      },
      // Chart.js v3+ Y轴配置写法
      y: {
        min: 0,
        max: 100,
        title: {
          display: true,
          font: {
            family: "Arial",
            size: 20
          },
          color: "#6c757d",
          text: "Moment"
        }
      }
    },
  };

  return (
    <div>
      <div>
        <Line data={data} options={options} width={400} height={200} />
      </div>
    </div>
  );
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 13:54:04