【发布时间】:2019-02-20 20:56:43
【问题描述】:
感谢 Sergio 推荐的答案。我真的很喜欢您演示的答案,但问题是由于每个错误,我仍然无法看到图表。这里使用的api是使用AWS的lambda函数
-
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.prototype.formatMMDDYYYY = () => { return ( this.getDate() + 1 + "/" + this.getMonth() + "/" + this.getFullYear() ); }; axios.get('https://cors-anywhere.herokuapp.com/https://api.myjson.com/bins/zfpa2') .then(results => { results.forEach(packet => { this.state.labels.push(new Date(packet.updated).formatMMDDYYYY()); this.state.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
从'react'导入反应,{组件}; 从'react-chartjs-2'导入{Bar};
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; -
包.json
{ "name": "apicharts", "version": "0.1.0", "private": true, "dependencies": { "axios": "^0.18.0", "chart.js": "^2.7.3", "jquery": "^3.3.1", "react": "^16.8.2", "react-chartjs-2": "^2.7.4", "react-dom": "^16.8.2", "react-scripts": "2.1.5", "react-vis": "^1.11.6" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": "react-app" }, "browserslist": [ ">0.2%", "not dead", "not ie <= 11", "not op_mini all" ] }
请帮我解决这个问题
【问题讨论】:
标签: javascript reactjs d3.js chart.js visualization