我制作了一个 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
会导致上述错误。