我正在使用 Chartjs 库在我的应用程序中显示图表。我在单独的组件中使用图表。当值被硬编码时,组件显示图表。我想传递来自其他组件的值并在不同的其他组件中使用相同的图表。图表未显示动态值。
const DoughnutChart = (props) => {
const chartRef = useRef(null);
const [wrong] = useState(props.wrong);
const [right] = useState(props.right);
useEffect(() => {
const data = {
datasets: [{
label: 'Result',
data: [wrong,right],
backgroundColor: [
'rgb(255, 0, 0)',
'rgb(0, 255, 0)',
],
}]
};
// Options for the chart
const options = {
plugins: {
title: {
display: true,
text: 'Exam Result'
}
}
};
// Create the chart instance
const myChart = new Chart(chartRef.current, {
type: 'doughnut',
data: data,
options: options
});
// Clean up function to destroy the chart when component unmounts
return () => myChart.destroy();
}, []);
return (
<div style={{width:300}}>
<canvas ref={chartRef}></canvas>
</div>
);
};
export default DoughnutChart;
该问题可能与您在值更改时处理组件更新的方式有关。 每当错误值和正确值发生变化时,您可能需要更新图表。您可以通过更新 useEffect 依赖项数组来实现这一点。
import { useEffect, useRef } from 'react';
import Chart from 'chart.js/auto';
const DoughnutChart = (props) => {
const chartRef = useRef(null);
useEffect(() => {
const data = {
datasets: [{
label: 'Result',
data: [props.wrong, props.right],
backgroundColor: [
'rgb(255, 0, 0)',
'rgb(0, 255, 0)',
],
}]
};
const options = {
plugins: {
title: {
display: true,
text: 'Exam Result'
}
}
};
// Check if chartRef is available before creating the chart
if (chartRef.current) {
const myChart = new Chart(chartRef.current, {
type: 'doughnut',
data: data,
options: options
});
// Clean up function to destroy the chart when component unmounts or values change
return () => myChart.destroy();
}
}, [props.wrong, props.right]);
return (
<div style={{ width: 300 }}>
<canvas ref={chartRef}></canvas>
</div>
);
};
export default DoughnutChart;