Chartjs with Nextjs - 用于绘制图形的用户输入

问题描述 投票:0回答:1

我在让用户输入为 nextjs 中的 chartjs 图表工作时遇到了很多麻烦。我遇到的关键问题是,每次数据集值更改时,整个图形都会重绘。这不是问题,除了我的图表在背景中有一个图像需要重新加载,导致图表闪烁。

我想我很接近,但我似乎无法让我的 Chart 对象存在于 useEffect() 挂钩之外。我基本上每次都需要销毁它,否则我会在重新加载时收到错误消息:

Canvas is already in use. Chart with ID '0' must be destroyed before the canvas with ID 'myChart' can be reused.

这是我的代码,也许你能帮帮我!为了清楚起见,我对其进行了简化。 QMl 值从父组件传递。

import Chart, { Title } from "chart.js/auto";
import { useEffect, useRef } from "react";

type ScatterPlotProps = {
  yValue;
};

type Coordinates = [
  {
    x: number;
    y: number;
  }
];

export const ScatterPlot = ({ QMl }: ScatterPlotProps) => {
  //const [data, setData] = useState([]);
  const chartRef = useRef();

  useEffect(() => {
    if (chartRef && chartRef.current && chartRef.current.getContext) {
      const data1: Coordinates = [
        {
          x: 10,
          y: QMl,
        },
      ];

      const data2: Coordinates = [
        {
          x: 20,
          y: QMl,
        },
      ];

      const scatterChart = new Chart(chartRef.current, {
        type: "scatter",

        data: {
          datasets: [
            {
              label: "Data1",
              data: data1,
              backgroundColor: "rgb(104, 202, 0)",
              borderColor: "rgb(104, 202, 0)",
            },
            {
              label: "Data2",
              data: data2,
              backgroundColor: "rgb(180, 180, 255)",
              borderColor: "rgb(180, 180, 255)",
            },
          ],
        },
      });
      // I can't render the chart in the first place without using this destroy command.. but then the object isn't available in the other useEffect hook?
      return () => {
        scatterChart.destroy();
      };
    }
  }, []);

  // HERE IS WHERE I'M HAVING TROUBLE
  useEffect(() => {
    scatterChart.data.datasets[0] = [
      {
        x: 10,
        y: QMl,
      },
    ];
  }, [QMl]);

  return <canvas ref={chartRef} />;
};
reactjs next.js react-hooks chart.js react-chartjs
1个回答
0
投票

如果你想在 React 中使用 chart.js,我建议使用 react-chartjs-2 插件:

https://react-chartjs-2.js.org/examples/scatter-chart

© www.soinside.com 2019 - 2024. All rights reserved.