创建新图表时,我无法销毁先前的图表。
问题是,如果 if(myChart) myChart.destroy()
从不触发。也许是因为myChart
变量仅存在于中useEffect
。
尽管myChart
可以将变量分配给状态,但是您将无法destroy()
直接调用状态。
那么,您将如何处理呢?
下面的示例根据以下值呈现饼图或条形图graphType
:
import React, { useEffect } from "react";
import Chart from "chart.js";
export default function GraphMaker({ graphType }) {
useEffect(() => {
const ctx = document.getElementById("myChart");
if (myChart) myChart.destroy()
if (graphType === "pie") {
console.log(myChart)
var myChart = new Chart(ctx, {
type: "pie",
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [
{
label: "# of Votes",
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
"Red",
"Blue",
"Yellow",
"Green",
"Purple",
"Orange"
],
borderColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
borderWidth: 1
}
]
}
});
}
else if (graphType === "bar") {
var myChart = new Chart(ctx, {
type: "bar",
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [
{
label: "# of Votes",
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
"Red",
"Blue",
"Yellow",
"Green",
"Purple",
"Orange"
],
borderColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
borderWidth: 1
}
]
}
});
}
}, [graphType])
return (
<>
<canvas id="myChart" />
</>
);
}
在新文档中,他们也使用此方法,他们通过销毁图表来解决此问题,以返回使用效果,如下所示:
useEffect(() => {
const cfg = {
type: 'doughnut',
data: {
labels: [
'Red',
'Blue',
'Yellow'
],
datasets: [{
label: 'My First Dataset',
data: [300, 50, 100],
backgroundColor: [
'rgb(255, 99, 132)',
'rgb(54, 162, 235)',
'rgb(255, 205, 86)'
],
hoverOffset: 4
}]
}
};
const chart = new Chart(canvas.current.getContext('2d'), cfg);
return () => chart.destroy();
});
通过实时示例链接到他们的文档:https : //www.chartjs.org/docs/master/charts/doughnut/
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句