如何在反应中使用实时图表?

How to use Real time chart in react?

我目前正在构建一个实时图表来测试它。我写了一些东西来接收数据作为例子,但它不起作用。下面是我的代码。

import { StreamingPlugin, ChartStreaming } from 'chartjs-plugin-streaming'
import {  
  Chart as ChartJS,
  LinearScale,
  CategoryScale,
  RadialLinearScale,
  BarElement,
  PointElement,
  LineElement,
  ArcElement,
  Legend,
  Tooltip
} from 'chart.js'
import {
  Chart,
  Line,
  Pie,
  Doughnut,
  Radar,
  getDatasetAtEvent,
  getElementAtEvent,
  getElementsAtEvent,
} from 'react-chartjs-2'
ChartJS.register(
  LinearScale,
  RadialLinearScale,
  CategoryScale,
  BarElement,
  PointElement,
  LineElement,
  ArcElement,
  StreamingPlugin, 
  Legend,
  Tooltip
)

const data =
{
  datasets :
  [
    {
      label : "real",
      backgroundColor : "rgb(255, 99, 132)",
      borderColor: "rgb(255, 99, 132)",
      fill : false,
      lineTension : 0,
      borderDash: [8,4],
      data : [],
      showLine: true,
    }
  ]
}
console.log(data.datasets[0].data)
const RealTime_ChartTest_options = 
{
  elements : 
  {
    line :
    {
      tesion: 0.5
    }
  },
  scales :
  {
    xAxes: [
      {
        type: "realtime",
        realtime: {
          onRefresh: function () {
            data.datasets[0].data.push({
              x: Date.now(),
              y: Math.random() * 100
            }
            );
          },
          delay: 300,
          refresh: 300
        }
      }
    ],
    yAxes: [
      {
        scaleLabel: {
          display: true,
          fontFamily: "Arial",
          labelString: "Moment",
          fontSize: 20,
          fontColor: "#6c757d"
        },
        ticks: {
          max: 100,
          min: 0
        }
      }
    ]
  }
}

const App = ()=>
{
  retrun(
   <Line data={data} options={RealTime_ChartTest_options} />
  )
}

因此,Y轴和标签显示正确,但数值没有实时存储在数据中,也没有绘制图表。

我在代码中做错了什么?

这是因为你的scale配置有误,你在使用V3的同时使用了V2的语法,改成这样应该可以解决问题:

scales: {
  x: {
    type: "realtime",
    realtime: {
      onRefresh: function() {
        data.datasets[0].data.push({
          x: Date.now(),
          y: Math.random() * 100
        });
      },
      delay: 300,
      refresh: 300
    }
  },
  y: {
    max: 100,
    min: 0
  }
}

对于所有更改,请阅读 migration guide