作者:mobiledu2502869077 | 来源:互联网 | 2023-09-13 12:40
我正在使用chart.js构建动态图表。
在componentDidmount中,我每秒通过setInterval调用getNewData()。
这将更新我的数据集中的数据,由于某种原因,状态更新时,图表不会更新/重新呈现。
添加新数据后,如何使图表更新其点?
组件代码:
import React,{Component} from 'react';
import { Line } from 'react-chartjs-2';
import 'chartjs-plugin-lineheight-annotation';
import './styles.scss';
export default class SmallCard extends Component {
constructor(props) {
super(props);
this.state = {
data: {
labels: ["1","2","3","4","5"],datasets: [
{
label: "Videos Made",backgroundColor: "rgba(255,255,0.75)",data: [4,5,1,10,32,2,12]
},{
label: "Subscriptions",backgroundColor: "rgba(0,data: [14,15,21,12,24,32]
}
]
}
}
}
componentDidmount() {
this.interval = setInterval(() => this.getNewData(),1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
getNewData() {
const min = 1;
const max = 10;
const rand = min + Math.floor(Math.random() * (max - min));
this.setState({
data: {
datasets: this.state.data.datasets.map((item,index) => ({
...item,data: [...this.state.data.datasets[index].data,rand]
}))
}
});
}
setGradientColour = (canvas,colour) => {
const ctx = canvas.getcontext('2d');
//console.log("ctx",ctx)
const gradient = ctx.createLinearGradient(0,400);
gradient.addColorStop(0,colour);
gradient.addColorStop(0.95,"rgba(133,144,0.85");
return gradient;
}
getchartData = canvas => {
const { data } = this.state;
if(data.datasets) {
let colors = ["rgba(255,"rgba(0,0.75)"];
data.datasets.forEach((set,i) => {
set.backgroundColor = this.setGradientColour(canvas,colors[i]);
set.borderColor = "white";
set.borderWidth = 2;
})
}
return data;
}
render() {
const data = this.state.data.datasets[1].data;
console.log("data",data)
return (
optiOns={{
responsive: true,lineHeightAnnotation: {
always: false,hover: true,color: 'white',noDash: true
}
}}
data={this.getchartData} />
)
}
}
getNewData
未绑定到类上下文,因此setState
将失败。您可以使用箭头功能,这样它将继承封闭的箭头。
getNewData = () => {
const min = 1;
const max = 10;
const rand = min + Math.floor(Math.random() * (max - min));
this.setState({
data: {
datasets: this.state.data.datasets.map((item,index) => ({
...item,data: [...this.state.data.datasets[index].data,rand]
}))
}
});
}