javascript - 使用chartjs时Rest Api数据获取错误
问题描述
我有关于api 数据获取的问题,我必须在 chartjs或数据可视化格式中表示数据。我正在尝试使用此 api 作为源来以图表格式表示数据,以准备好我的仪表板,该仪表板正在为数据分析视角做好准备。请帮助我,我知道我落后了一小部分。
应用程序.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;
图表.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;
解决方案
- 如果你想为一个对象的实例继承一个新的自定义方法,你需要在原型中定义它们,所以我们不能使用箭头函数而不是
Date.formatMMDDYYYY = () => {...}
使用 this ,因为那样我们将无法获得正确的值。此外,您也可以使用接收 Date 并在需要时调用它的普通函数,这种方式更加简单和安全。Date.prototype.formatMMDDYYYY = function{...}
this
- 关于方法返回的格式字符串中的顺序的小错误,而不是
this.getDate() + 1 + "/" + this.getMonth() +...
应该是this.getMonth() + 1 + "/" + this.getDate() +...
- 您正在尝试从中获取数据
results
,但数据不存在results.data
,因此周期应该是results.data.forEach(packet => {...}
推荐阅读
- haskell - 当它们都是同一类的所有实例时,如何将函数应用于异构列表的所有元素?
- r - 通过有条件地过滤 R 中的数据框来添加二进制列的任何快速方法?
- javascript - 如何使用 MDBDataTable 从已经在 props 中的 api 获取数据
- typescript - Typescript 泛型:如何确保函数 args 相互匹配?
- r - 在R中的向量上应用函数
- javascript - 由于 Cookie 的“SameSite”和“安全”设置,Google Analytics 在 IFrame 中被阻止
- javascript - Angular 8 在点击时使用 ngFor 切换 CSS 类
- string - 未处理的异常:“字符串”类型不是“列表”类型的子类型
'的'价值' - c++ - 队列基本函数(put)调用(程序崩溃)
- java - 从 Spring Data JpaRepository 返回 @id 字段