我有一个与api的数据提取相关的问题,其中我必须以chartjs或数据可视化的格式表示数据。我正在尝试使用此api作为源代表以图表格式表示数据,以便为我的仪表板做好准备,该仪表板已准备好进行数据分析。请帮助我,我知道我有一点滞后。
import React, { Component } from "react";
import axios from "axios";
import Chart from "./chart";
class App extends Component {
constructor() {
super();
this.state = {
labels: [],
data: []
};
}
componentDidMount() {
this.getChartData();
}
getChartData() {
Date.formatMMDDYYYY = () => {
return (
this.getDate() + 1 + "/" + this.getMonth() + "/" +
this.getFullYear()
);
};
axios
.get("https://cors-anywhere.herokuapp.com/https://api.myjson.com/bins/chnmi"
)
.then(results => {
// Split timestamp and data into separate arrays
const labels = [];
const data = [];
results.forEach(packet => {
labels.push(new Date(packet.updated).formatMMDDYYYY());
data.push(parseFloat(packet.users));
});
this.setState({ data, labels });
})
.catch(error => {
console.log(error);
});
}
render() {
return (
<div>
<Chart labels={this.state.labels} data={this.state.data} />
</div>
);
}
}
export default App;
import React, { Component } from 'react';
import {Bar} from 'react-chartjs-2';
class Chart extends Component {
render() {
const chartData = {
labels: this.props.labels,
datasets: [
{
data: this.props.data,
backgroundColor: 'rgba(255, 99, 132, 0.6)',
}
]
}
return (
<div className="chart">
<Bar
data={chartData}
options={{
title: {
display: true,
text: 'Largest cities in Delhi',
fontSize: 25
},
legend: {
display: true,
position: 'right'
}
}}
/>
</div>
);
}
}
export default Chart;
Date.formatMMDDYYYY = () => {...}
使用箭头函数,因为我们不会得到正确的值为Date.prototype.formatMMDDYYYY = function{...}
。此外,您可以使用收到Date的普通函数,并在需要时调用它,这种方式更简单,更安全。this
它应该是this.getDate() + 1 + "/" + this.getMonth() +...
this.getMonth() + 1 + "/" + this.getDate() +...
获取数据,但数据不在results
,所以循环应该是results.data
修正了代码:results.data.forEach(packet => {...}