Chartjs with Nextjs -用户输入绘图图形



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

我想我很接近,但我似乎无法让我的图表对象存在于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} />;
};

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

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

最新更新