首页 > 解决方案 > 使用chartjs时Rest Api数据获取错误

问题描述

我有关于api 数据获取的问题,我必须在 chartjs或数据可视化格式中表示数据。我正在尝试使用此 api 作为源来以图表格式表示数据,以准备好我的仪表板,该仪表板正在为数据分析视角做好准备。请帮助我,我知道我落后了一小部分。

  1. 应用程序.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;
    
  2. 图表.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;
    

标签: javascriptjsonreactjschart.jsdata-visualization

解决方案


  1. 如果你想为一个对象的实例继承一个新的自定义方法,你需要在原型中定义它们,所以我们不能使用箭头函数而不是Date.formatMMDDYYYY = () => {...}使用 this ,因为那样我们将无法获得正确的值。此外,您也可以使用接收 Date 并在需要时调用它的普通函数,这种方式更加简单和安全。Date.prototype.formatMMDDYYYY = function{...}this
  2. 关于方法返回的格式字符串中的顺序的小错误,而不是this.getDate() + 1 + "/" + this.getMonth() +...应该是this.getMonth() + 1 + "/" + this.getDate() +...
  3. 您正在尝试从中获取数据results,但数据不存在results.data,因此周期应该是results.data.forEach(packet => {...}

此处修复代码:https ://codesandbox.io/s/p3q2pz2l8x


推荐阅读