【发布时间】:2019-12-17 13:06:57
【问题描述】:
我正在尝试通过首先从 axios 请求中检索一些数据来制作图表,因此我可以显示图表但它保持为空。当我两次单击图例时,它确实显示了数据,但我想立即显示数据。任何人都可以看看我的代码?我一直在努力创建图表几个小时,因为我无法通过状态发送数据,但现在应该“修复”。当然,除了双图例点击问题..
这是我要加载图表的页面:
import React, { Component, Fragment } from 'react';
import axios from 'axios';
import Chart from "./Chart.js";
export default class extends Component {
state = {
packageData: {}
}
async getData() {
let count = [];
await axios.get(`/getCountExpress`)
.then(res => {
count.push(res.data[0].count);
});
await axios.get(`/getCountEconomy`)
.then(res => {
count.push(res.data[0].count);
});
await axios.get(`/getCountInternational`)
.then(res => {
count.push(res.data[0].count);
});
return Promise.all(count);
}
componentWillMount() {
let types = [];
this.getData().then(values => {
values.forEach(value => types.push(value));
});
this.setState({
packageData: {
labels: ['Express', 'Economy', 'International'],
datasets: [{
label: 'Amount of packages',
data: types,
backgroundColor: [
'rgba(255, 0, 0, 1)',
'rgba(38, 166, 91, 1)',
'rgba(44, 130, 201, 1)']
}]
}
}, () => {
console.log(this.state.packageData.datasets);
});
}
render() {
return (
<Fragment>
<h2 style={{ textAlign: 'center', marginTop: '20px' }}>Statistics</h2>
<Chart chartData={this.state.packageData} />
</Fragment>
);
}
}
这是我的图表组件:
import React, { Component } from 'react';
import { Bar } from 'react-chartjs-2';
export default class Chart extends Component {
constructor(props) {
super(props);
this.state = {
chartData: props.chartData
}
}
options = {
responsive: true,
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
render() {
return (
<div className="chart">
<Bar
data={this.state.chartData} options={this.options}
/>
</div>
)
}
}
所以有人知道问题可能是什么吗?为什么不立即加载数据?
【问题讨论】:
标签: reactjs charts react-chartjs