我为此编写了一个 React 应用程序,我有一个名为 cardContainer
的组件,其中我包含了另一个名为 chartContainer
的组件,它使用 chart.js
在仪表板中呈现图表。< /p>
下面是cardContainer里面的代码
render() {
return(
<div className="site-card-wrapper">
<Row gutter={16}>
{cardList.map(card =>
<Col span={card.size}>
<Card>{card.title}
<ChartContainer
data={card.dataSet.chartData ? card.dataSet.chartData : []}
label={card.dataSet.chartLabel ? card.dataSet.chartLabel : "No Lebel"}
backgroundColor={card.dataSet.chartBackgroundColor ? card.dataSet.chartBackgroundColor : []}
borderColor={card.dataSet.chartBorderColor ? card.dataSet.chartBorderColor: []}
/>
</Card>
</Col>
)}
</Row>
</div>
);
}
}
此 <ChartContainer>
类具有在 chartContainer 内消耗并呈现图表的道具。图表容器代码如下。
import React, {Component} from 'react';
import { Line } from 'react-chartjs-2';
class ChartContainer extends Component {
constructor(props) {
super(props)
this.state = {
data: this.props.data,
label: this.props.label,
backgroundColor: this.props.backgroundColor,
borderColor: this.props.borderColor
}
}
render() {
const { data, label, backgroundColor, borderColor } = this.state
return (
<div>
<Line
height={200}
data={{
labels:['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: label,
data: data,
backgroundColor: backgroundColor,
borderColor: borderColor,
borderWidth: 1
}]
}}
options={{
maintainAspectRatio:false,
scales: {
xAxes: [{
gridLines: {
color: 'rgba(255, 255, 255, 0.1)',
},
}],
yAxes: [{
gridLines: {
color: 'rgba(255, 255, 255, 0.1)',
},
ticks: {
// min: 0,
// max: 200,
fontColor: 'rgba(255, 255, 255, 0.5)',
}
}]
}
}}
/>
</div>
);
}
}
export default ChartContainer;
错误是当我使用路由器在页面之间切换时,图表会被附加。例如,此图表最初显示在仪表板页面中。当我切换到另一个页面并且当我回到同一个仪表板页面时,新图表与旧图表一起显示,通过附加到旧图表而不是清除和呈现新图表。在这种情况下,每次在页面之间切换时,图表计数都会翻倍,并且图表计数变为 1、2、3、4……但我只想显示一张图表。提前致谢。