Chart.js柱状图不显示问题求助
Chart.js Bar组件柱状图无法显示问题解决
问题现象
使用Chart.js的Bar组件时,仅能看到图表标题和图例,柱状条完全无法显示。
现有代码
组件渲染代码
render() { return ( <div> <div> <Bar data={this.traffic_chart} options={{ responsive: true, scales: { x: { stacked: true }, y: { stacked: true } }, plugins: { title: { display: true, text: "the current traffic change based on the 30 day internet trends data point", fontSize: 20 }, legend: { display: true, position: "right" } } }} /> </div> </div> ) }
图表数据初始化
this.traffic_chart = { labels: [], datasets: [{ label: "Total", backgroundColor: "rgba(255, 99, 132, 0.5)", //borderColor: "rgba(19,89,64,1)", //borderWidth: 2, data: [] }, { label: "Http", backgroundColor: "rgba(53, 162, 235, 0.5)", //borderColor: "rgba(19,53,65,1)", //borderWidth: 2, data: [] }] }
数据填充逻辑
在componentDidMount()方法中填充数据,控制台打印显示labels为日期数组,Total和Http的data也对应有数值,但图表仍无柱状条显示。
问题原因
直接修改挂载在this上的traffic_chart对象属性(如给labels、data数组push数据),不会触发React组件的重渲染。Chart.js组件初始化时拿到的是空数据对象,后续数据更新后没有通知到组件,因此不会渲染柱状条。
解决方案
改用React的state来管理图表数据,通过setState更新数据触发组件重渲染,具体修改如下:
1. 初始化状态
constructor(props) { super(props); this.state = { trafficChart: { labels: [], datasets: [{ label: "Total", backgroundColor: "rgba(255, 99, 132, 0.5)", data: [] }, { label: "Http", backgroundColor: "rgba(53, 162, 235, 0.5)", data: [] }] } }; }
2. 数据更新逻辑
componentDidMount() { // 替换为你的实际数据获取逻辑 const fetchedLabels = ["2024-05-01", "2024-05-02", "2024-05-03"]; const totalData = [120, 190, 230]; const httpData = [80, 150, 180]; this.setState({ trafficChart: { ...this.state.trafficChart, labels: fetchedLabels, datasets: [ { ...this.state.trafficChart.datasets[0], data: totalData }, { ...this.state.trafficChart.datasets[1], data: httpData } ] } }); }
3. 更新渲染代码
render() { return ( <div> <div> <Bar data={this.state.trafficChart} options={{ responsive: true, scales: { x: { stacked: true }, y: { stacked: true } }, plugins: { title: { display: true, text: "基于30天互联网趋势数据的当前流量变化", fontSize: 20 }, legend: { display: true, position: "right" } } }} /> </div> </div> ); }
通过上述修改,数据更新时会触发组件重渲染,Bar组件拿到最新的完整数据后就能正常显示柱状条了。
内容的提问来源于stack exchange,提问作者Murphy
相关产品推荐
相关产品推荐

