我使用reactjs和axios加载并显示来自API端点的数据以生成折线图,我有两个API端点;一个用于今年的数据,另一个用于去年的数据。我有2个带有“今年”和“去年”年份的跨度,在单击时应获取api数据,但是我的问题是我必须双击一个跨度才能加载它,而且即使双击也要加载非常缓慢的数据
{
state = {
months: [],
hours: [],
teamhours: [],
thisYear: true
};
componentDidMount() {
// post data
if (this.state.thisYear === true) {
axios.get('/api/hours-data')
.then((response) => {
this.setState({
errors: {},
loading: true,
months: response.data.labels,
hours: response.data.hours,
teamhours: response.data.teamhours
});
})
.catch((error) => {
let errors = null;
if (Object.assign({}, error) && Object.assign({}, error).response && Object.assign({}, error).response.data) {
errors = Object.assign({}, error).response.data;
}
// show validation errors
this.setState({
errors: errors || {},
loading: false
});
});
} else {
axios.get('/api/hours-data-last-year')
.then((response) => {
this.setState({
errors: {},
loading: true,
months: response.data.labels,
hours: response.data.hours,
teamhours: response.data.teamhours
});
})
.catch((error) => {
let errors = null;
if (Object.assign({}, error) && Object.assign({}, error).response && Object.assign({}, error).response.data) {
errors = Object.assign({}, error).response.data;
}
// show validation errors
this.setState({
errors: errors || {},
loading: false
});
});
}
}
lastYearStateHandler = () => {
this.setState({ thisYear: false });
this.componentDidMount();
};
thisYearStateHandler = () => {
this.setState({ thisYear: true });
this.componentDidMount();
};
render() {
if (!this.state.hours || this.state.hours.length === 0) {
return (
<div className="charts">
<Loader
type="Watch"
color="#1059ce"
height="150"
width="150"
/>
</div>
);
}
const hoursData = {
datasets: [
{
label: 'Your hours',
backgroundColor: 'rgb(5,136,193,0.5)',
data: this.state.hours,
position: top
},
{
label: 'Team hours (average)',
backgroundColor: 'rgb(162, 65, 146,0.5)',
data: this.state.teamhours,
position: top
}
],
labels: this.state.months
};
const options = {
responsive: true,
scaleBeginAtZero: true,
scaleShowGridLines: true,
scaleGridLineColor: 'rgba(0, 0, 0, .1)',
scaleGridLineWidth: 1,
scaleShowHorizontalLines: true,
scaleShowVerticalLines: true,
barShowStroke: true,
barStrokeWidth: 2,
barValueSpacing: 5,
barDatasetSpacing: 1
};
return (
<div>
<div className="fields-holder charts">
<h2>Time worked</h2>
<div className="charts__span">
<span id="last_year" onClick={this.lastYearStateHandler}>Last year</span>
<span id="this_year" onClick={this.thisYearStateHandler}>This year</span>
</div>
<Line
data={hoursData}
options={options}
width="800"
height="450"
/>
</div>
</div>
);
}