Javascript 当图表表示为react JSX元素时,如何清除/销毁Chart.js画布
我在chart.js中遇到了这个问题,在这里我有一个关于特定报告的图表。当我将页面切换到另一个包含chartjs元素的页面并切换回时,图表在图表数据点上显示数据标签为“x:number,y:number”。 在读了一些关于这方面的内容后,我相信这是因为当我切换回原始图表时画布没有被正确重置。 我发现的使用clear()或destroy()命令的修复示例引用了图表画布。 例子: 然而,在react中,这一点要复杂一些。 我的问题是,如何在绘制图形之前清除画布。下面是用于绘制图表的图表组件Javascript 当图表表示为react JSX元素时,如何清除/销毁Chart.js画布,javascript,reactjs,canvas,chart.js,Javascript,Reactjs,Canvas,Chart.js,我在chart.js中遇到了这个问题,在这里我有一个关于特定报告的图表。当我将页面切换到另一个包含chartjs元素的页面并切换回时,图表在图表数据点上显示数据标签为“x:number,y:number”。 在读了一些关于这方面的内容后,我相信这是因为当我切换回原始图表时画布没有被正确重置。 我发现的使用clear()或destroy()命令的修复示例引用了图表画布。 例子: 然而,在react中,这一点要复杂一些。 我的问题是,如何在绘制图形之前清除画布。下面是用于绘制图表的图表组件 cont
cont Chart: FunctionComponent<Props> = ({data}) => {
const options = (): ChartOptions => ({
responsive: true,
maintainAspectRatio: false,
legend: {
display: false
},
tooltips: chartTooltips,
elements: chartElementsNoLines,
scales: {
xAxes: [
{
display: true,
id: 'x-axis-0',
ticks: {
suggestedMin: minMax.min,
suggestedMax: minMax.max,
maxTicksLimit: 7,
maxRotation: 0,
fontFamily: 'Roboto, sans-serif',
fontSize: 10,
autoSkip: true,
callback: value => currency(value, { precision: 0 }).format()
},
gridLines: {
display: false
}
}
],
yAxes: [
{
type: 'linear',
display: false,
ticks: {
min: 0,
max: maxY
},
id: 'y-axis-0',
gridLines: {
display: false
}
}
]
}
})
return (
<section>
<div className={classes.chartContainer}>
<HorizontalBar
data-cy="limit-chart"
data={data}
options={{ ...options(), ...annotationPlugin() }}
redraw={true}
height={80}
/>
</div>
</section>
)
}
cont-Chart:FunctionComponent=({data})=>{
常量选项=():图表选项=>({
回答:是的,
MaintaintAspectRatio:false,
图例:{
显示:假
},
工具提示:图表工具提示,
元素:图表元素线条,
比例:{
xAxes:[
{
显示:对,
id:'x轴-0',
滴答声:{
建议最小值:minMax.min,
建议最大值:minMax.max,
马克斯:7,
最大旋转:0,
fontFamily:“机器人,无衬线”,
尺寸:10,
autoSkip:是的,
回调:value=>currency(值,{precision:0}).format()
},
网格线:{
显示:假
}
}
],
雅克斯:[
{
类型:'线性',
显示:假,
滴答声:{
分:0,,
马克斯:马克斯
},
id:'y轴-0',
网格线:{
显示:假
}
}
]
}
})
返回(
)
}
我在重新提交时遇到了数据和大小更改的问题,我找到了一种方法,使用ref(profitChartRef.current.chartInstance.destroy();)强制更新它,以销毁chartInstance,然后呈现完全反映已更新内容的全新实例
export const ProfitReportChart = () => {
const profitChartRef = useRef();
if (profitChartRef?.current) {
profitChartRef.current.chartInstance.destroy();
}
return <Bar ref={profitChartRef} data={data} options={options} redraw/>;
}
export const ProfitReportChart=()=>{
const profitChartRef=useRef();
if(profitChartRef?电流){
profitChartRef.current.chartInstance.destroy();
}
返回;
}