这是我的 React 组件脚本,
它没有显示
label
,但是数据集是正确的,
所以我猜这是
update
的问题?
我真的很感激任何提示,
import React,{useRef,useState,useEffect} from 'react'
import axios from 'axios';
import styles from "../css/test-styles.module.css";
import { Line } from 'react-chartjs-2';
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend,
} from 'chart.js'
ChartJS.register(
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend
)
const DashboardPage = (props) =>{
const data = useRef();
const chartRef = useRef();
const [labels,setLabels] = useState([]);
const options = {
responsive: true,
plugins: {
legend: {
position: 'top'
},
title: {
display: true,
text: 'Chart.js Line Chart',
},
},
};
useEffect(()=>{
data.current = {
//labels:["june","july","august"],
labels:labels,
datasets: [
{
label: 'Dataset 1',
data: [100,200,300],
borderColor: 'rgb(255, 99, 132)',
backgroundColor: 'rgba(255, 99, 132, 0.5)',
},
{
label: 'Dataset 2',
data: [350,150,250,100,200],
borderColor: 'rgb(53, 162, 235)',
backgroundColor: 'rgba(53, 162, 235, 0.5)',
},
],
};
console.log("data",data.current); //data is correctly set
console.log("chartref",chartRef);
chartRef.current?.update();// it not work??
},[labels])
useEffect(()=>{
const now = new Date();
const OLDEST_DATE = new Date(2025, 0, 3)
const resultDates = [];
for (let date = OLDEST_DATE; date <= now; date.setDate(date.getDate() + 1)) {
resultDates.push(new Date(date));
}
console.log(resultDates);
var arr = resultDates.map((d)=>{
return d.getMonth().toString() + "/" + d.getDate().toString();
})
console.log(arr);
setLabels(arr);
},[])
return (
<div className={styles.wrapper} style={{padding:"10px"}}>
{data.current &&
<Line ref={chartRef} options={options} data={data.current}/>}
</div>
);
}
export default DashboardPage;
一个快速解决方案是使用
useState()
,以便在更新值时重新渲染图表。
const [chartData, setChartData] = useState({});
useEffect(() => {
...
setChartData(data.current);
//chartRef.current?.update(); // Don't need to update manually
}, [labels]);
<div style={{ padding: '10px' }}>
{data.current && (
<Line ref={chartRef} options={options} data={chartData} />
)}
</div>