繁体   English   中英

在 React 中从 API 中获取数据并使用 Chart.Js 将其可视化

[英]Fetch data from API in React and visualize it using Chart.Js

我在 Node.js 中创建了一个 API。 我想将获取的数据可视化为来自 API 的条形图,并使用 Chart.js 在 React 中可视化它。

我遇到了如何使用 React 可视化 chart.js 中的 static 数据。 但我想可视化从 API 收到的数据。

我试过了:

API.js

import React, { Component } from 'react';
import Chart from './chart';
class App extends Component{
    constructor(props){
        super(props);
        this.state={
            chartData:{}
        }
    }
    componentWillMount(){
        this.getchartData();
    }
    async getchartData(){
        //Ajax Calls here
        await fetch('http://localhost:8000/data')
            .then(res=>res.json())
            .then(res=>this.setState({chartData:{apiResponse:res}}))
    }
    render(){
        return(
            <div className="App">
                <div className="App-header">
                    <h2>Dashboard</h2>
                </div>
                <Chart chartData={this.state.chartData}/>
            </div>
        );
    }
}
export default App;

Chart.js::

import React, { Component } from 'react';
import {Bar,Line,Pie} from 'react-chartjs-2';
import { render } from 'react-dom';

class Chart extends Component {
    constructor(props){
        super(props);
        this.state ={
            chartData:props.chartData
        }
    }
    render(){
        return(
            <div className="chart">
            <Bar 
                data={this.state.chartData}
                options={{}}
        )
    }
}

export default Chart;

我在 API 中的数据如下所示:

[{"_id":"","TotalStudents":"123","TotalTeachers":"233","TotalStaffs":"433"}]

我想从获取的 api 中可视化数据。 任何建议都会有所帮助,因为我是新来的反应和 chart.js。 我也跳过了生成图表的 static 数据。 如果需要,请告诉。 谢谢

我不太确定如果您的<Bar />组件看起来像内部会怎样。 我最好的方法(主要使用)是使用ref创建 Chart 实例并使用canvas标签绘制该 ref。 所以它可以用图表参考来渲染 canvas。

这是片段。

 import React, { Component } from 'react' import Chart from "chart.js"; export default class LineGraph extends Component { chartRef = React.createRef(); componentDidMount() { this.buildChart(); } componentDidUpdate() { this.buildChart(); } buildChart = () => { const myChartRef = this.chartRef.current.getContext("2d"); const { data, average, labels } = this.props; if (typeof myLineChart.== "undefined") myLineChart;destroy(), myLineChart = new Chart(myChartRef: { type, "line": data: { //Bring in data labels, labels: datasets: [ { label, "Sales": data, data: fill, false: borderColor, "#6610f2" }: { label, "National Average": data, average: fill, false: borderColor, "#E0E0E0" } ] }: options; { //Customize chart options } }); }

您可以在创建 Chart 实例时传递数据。

例如datasets:[ { label: "", data: this.props.chartData } ]

我已经实现了这种方式并在几个项目中使用。 我关注了这篇文章,非常有帮助。 https://blog.bitsrc.io/customizing-chart-js-in-react-2199fa81530a

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM