我创建了一个React.JS组件,它使用react-chartjs
库周围的chart.js
包装器绘制图表。我在更新时收到错误,好像我的数据已损坏。我想也许是因为我没有看到我的代码有什么问题。当第一次绘制图表时,它显示正常。 setState
导致:Uncaught Type Error: Cannot read property 'points' of undefined(...)
发生在core.js
内的set.data.forEach()
匿名函数中。
以下是我的代码:
class Usage extends Component {
constructor(props) {
super(props);
this.state = {
active: true,
new: false,
chartData: []
}
}
componentWillMount() {
this.buildChartData();
}
buildChartData() {
const daysInMonth = 30;
const graphs = [
{title: 'Active Users', key: 'active', color: 'rgba(255, 99, 132, 1)'},
{title: 'New Users', key: 'new', color: 'rgba(50, 25, 255, 1)'}
];
let datasets = [];
let labels = [];
let labelsDone = false;
graphs.forEach((graph) => {
if (this.state[graph.key]) {
let data = [];
let backgroundColor = [];
let borderColor = [];
// XXX !!! for now
if (!labelsDone) {
for (let i = daysInMonth; i > 0; i--) {
let d = new Date();
// we stop yesterday
d.setDate(d.getDate() - i);
labels.push( (d.getUTCMonth() + 1) + '/' + d.getUTCDate() );
}
}
labelsDone = true;
for (let i = daysInMonth; i > 0; i--) {
let d = new Date();
// we stop yesterday
d.setDate(d.getDate() - i);
data.push( Math.round(Math.random() * 200));
borderColor.push(graph.color);
backgroundColor.push('rgba(0,0,0,0)');
}
let dataset = {
data: data,
borderWidth: 1,
label: graph.title,
fillColor: 'rgba(0,0,0,0.0)',
strokeColor: borderColor
};
datasets.push(dataset);
}
})
this.setState({
chartData: {datasets: datasets, labels: labels}
});
}
toggleCheckbox = label => {
switch(label) {
case 'Active Users':
this.setState({
active: !this.state.active
});
break;
case 'New Users':
this.setState({
new: !this.state.new
});
break;
default:
console.log('Error: unhandled action');
break;
}
this.buildChartData();
}
render() {
return (
<div style={{display: 'flex', flexDirection: 'row'}}>
<div style={{flexDirection: 'column', marginLeft: '50px', marginRight: '50px', flexGrow: 1}}>
<div style={{height: '20vh'}}>
<div style={{flexDirection: 'row'}}>
<Checkbox
label={'Active Users'}
handleCheckboxChange={this.toggleCheckbox}
isChecked={true}
/>
<Checkbox
label={'New Users'}
handleCheckboxChange={this.toggleCheckbox}
isChecked={false}
/>
</div>
</div>
<div style={{height: '75vh'}}>
<Line data={this.state.chartData} options={chartOptions} />
</div>
</div>
</div>
);
}
}
export default Usage;
我打印出较小的数据集,同样的事情发生了。除了随机生成的值之外,不要看到任何差异。尽管如此,初始渲染仍然很好,但setState
,我理解调用update
会导致上述错误。
答案 0 :(得分:2)
如果传入组件的数据发生变化,则使用chart.js'.update()在点之间设置动画。如果您希望在每次更改时销毁并重新绘制图表,请将重绘作为道具传递。例如<LineChart data={this.state.chartData} redraw />
添加redraw
可以解决问题。