英文:
On hover data fluctuation issue in chart.js graph react js .How can i fix this?
问题
如果我使用 event: [],那么悬停问题将会解决,但我也想要工具提示。
请告诉我或者给出一个例子,我如何在显示另一个客户数据之后销毁我的图表。我无法在 useEffect 中销毁它,因为如果我在控制台中打印 myChart,它会返回 undefined 值。
英文:
If i use event:[] then hover issue will fix, but i also want tooltip.
import Chart from "chart.js";
const Component1 = ({productData,truncatedNames}) => {
useEffect(() => {
const canvas = document.getElementById("myChart1");
// Create the chart context
const ctx = canvas.getContext("2d");
// Define the chart data
const data = {
labels: truncatedNames,
datasets: [
{
label: "Products",
data: productData,
backgroundColor: "#FA7070",
},
],
};
// Configure the chart options
const options = {
responsive: true,
scales: {
yAxes: [
{
display: true,
ticks: {
suggestedMin: 0,
beginAtZero: true,
callback: productData ? yAxisLabelCallback : emptyFunction,
},
},
],
},
onHover: function (event, chartElements) {},
hover: false,
};
// Create the bar chart
const myChart = new Chart(ctx, {
type: "bar",
data: data,
options: options,
});
}, []);
return (
<Box>
<canvas width={"70%"} height={"40%"} id="myChart1"></canvas>
</Box>
);
};
export default Component1;
Please tell or give any example how I destroy my chart after displaying another customer data.
I am unable to destroy this in useEffect because if i console myChart then it gives undefined value.
答案1
得分: 1
如评论中所述,
由于您没有将依赖项(productData 和 truncatedNames)传递给 useEffect,所以您的组件不会使用新数据进行刷新。
依赖项将在属性更改后重新运行效果。
useEffect(() => {
... 其他代码
// 创建柱状图
const myChart = new Chart(ctx, {
type: "bar",
data: data,
options: options
});
return () => {
// 执行清理操作
myChart.destroy();
};
}, [productData, truncatedNames]);
此外,您还需要添加一个清理函数,该函数将销毁旧图表并在 useEffect 中呈现新图表。
英文:
As mentioned in the comments,
Your component is not refreshed with new data because you are not passing dependancies (productData and truncatedNames) to the use effect.
The dependancies will rerun the effect after props are changed.
useEffect(() => {
... Other code
// Create the bar chart
const myChart = new Chart(ctx, {
type: "bar",
data: data,
options: options
});
return () => {
// doing cleanup
myChart.destroy();
};
}, [productData, truncatedNames]);
Also you need to add clean up function which will destroy the old chart and render new one in the useEffect.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论