[英]Chart not updating after data change in react chartjs
I made a line chart with react chartjs.我用 react chartjs 制作了一个折线图。 The chart is working perfectly fine but when I try to update the chart, it didn't get updated.
图表工作得很好,但是当我尝试更新图表时,它没有得到更新。 Although I am able to change the data of the chart.
虽然我能够更改图表的数据。 Please help.
请帮忙。 I try to update the chart on the legend click.
我尝试在图例单击时更新图表。 I go through some tutorials and see like update function will help me.
我浏览了一些教程,发现更新功能对我有帮助。 But when I try the update function with my line, it shows an error with 'undefined update function'.
但是当我用我的线路尝试更新函数时,它显示了一个错误,“未定义的更新函数”。
import React from 'react';
import {Line} from 'react-chartjs-2';
const checkinsData={
labels:['4 P.M','5 P.M','6 P.M','7 P.M','8 P.M','9 P.M','10 P.M','11 P.M','12 A.M','1 A.M','2 A.M','3 A.M','4 A.M'],
datasets:[
{
label:"Day",
backgroundColor:"blue",
borderColor:'#333',
borderWidth:2,
lineTension:0.1,
fill:true,
data:[4,5,6,7,8,9,10,11,12,1,2,3,4]
}
]
}
class CheckinGraph extends React.Component{
constructor(props)
{
super(props)
this.state={
}
}
legendClick=function() {
console.log("Legend click"+ checkinsData.labels);
checkinsData.datasets.data=[100,120,200,25,56,78,80,90,70,100];
}
render()
{
return(
<div className="col-md-12 default-shadow bg-white pd-30-0 border-radius-10 align-center">
<Line
redraw
data={checkinsData}
options={
{
title:{
text:'Total Check-ins',
fontSize:20,
display:true
},
legend:{
display:true,
position:'top',
onClick:this.legendClick
}
}
}
/>
</div>
)
}
}
export default CheckinGraph;
Your chart will update/re-render when your component will get new props or state will be updated.当您的组件获得新道具或状态更新时,您的图表将更新/重新渲染。 Since your chart data that you are updating it not in state of the component, so component don't know about the change and it is not re-rendering your chart.
由于您正在更新的图表数据不在组件的状态下,因此组件不知道更改并且不会重新呈现您的图表。 You need to tell the component that something has changed and now time to re-render.
您需要告诉组件某些内容发生了变化,现在是重新渲染的时候了。 This can be achieved by: 1. adding your data in state and then updating the data on click but in a right way (without mutating the state) 2. Added a random key in state and update the state key after updating the non-state data
这可以通过以下方式实现: 1. 在状态中添加数据,然后在单击时以正确的方式更新数据(不改变状态) 2. 在状态中添加随机密钥并在更新非状态后更新状态密钥数据
state = { key: Date.now() } legendClick=function() { console.log("Legend click"+ checkinsData.labels); checkinsData.datasets[0].data=[100,120,200,25,56,78,80,90,70,100]; this.setState({ key: Date.now() }); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.