【发布时间】:2019-02-24 18:01:21
【问题描述】:
我有关于数据获取api的问题,我必须在chartjs中表示数据或数据可视化的格式。 我正在尝试使用此 api 作为源来以图表格式表示数据,以准备好我的仪表板,该仪表板正在为数据分析视角做好准备。请帮助我,我知道我有点落后。
-
App.js
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; -
chart.js
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;
【问题讨论】:
-
您遇到了什么错误?
-
我无法以 chartjs 格式显示数据。我想代表数据。您可以查看此链接了解更多信息:codesandbox.io/embed/82y7nl2pl0?fontsize=14
标签: javascript json reactjs chart.js data-visualization