首页 > 解决方案 > 如何使用 API 数据正确更新 React & Chart.js 应用程序中的图表

问题描述

我正在从 API 接收数据,我想获取该数据并将其填充到我的图表中。我可以看到调用 API 数据的位置并将其传递给 setState,但我似乎无法正确获取这些数据并将其传递给我的图表。

我尝试使用 Chart.js 的 destroy() 和 update() 方法无济于事。我确信这只是我没有在我的应用程序中正确使用它们的问题。下面的代码不包括这些方法,因为我不确定在哪里使用它们。我还尝试将 API 数据推送到图表的数据数组中,但没有成功。

componentDidMount() {
// create chart 
          new Chart(myChartRef, {
      type: "line",
      data: {
        labels: ["Jan", "Feb", "March"],
        datasets: [
          {
            data: this.state.chartData,
            backgroundColor: gradient,
            pointBackgroundColor: "#fff",
            pointBorderColor: gradient,
            pointRadius: "5",
            hoverBackgroundColor: "#75C6FF",
            hoverBorderColor: gradient
          }
        ]
      },
      options: {
        responsive: true,
        legend: {
          display: false
        },
        scales: {
          xAxes: [
            {
              gridLines: {
                color: "#535356"
              },
              ticks: {
                fontColor: "#87889C"
              }
            }
          ],
          yAxes: [
            {
              gridLines: {
                color: "#535356"
              },
              ticks: {
                fontColor: "#87889C"
              }
            }
          ]
        }
      }
    });
/* fetch API data and use it to set app state (setState) */
    const getChartData = () => {
      fetch(
        "https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,ETH&tsyms=USD"
      )
        .then(response => {
          return response.json();
        })
        .then(myJson => {
          const bitcoinPrice = myJson.BTC.USD;
          this.setState({ chartData: bitcoinPrice });
          console.log(JSON.stringify(myJson));
        });
    };

    getChartData();
}

在代码中,一旦安装了组件,我就会创建一个新图表。然后我调用 API 并接收我想在图表上显示的数据。我可以在 React 开发工具中看到状态正在我的应用程序中设置,但图表没有更新。我假设我需要做一些事情,比如将 API 数据映射到图表中的数据数组中,但我不确定如何正确执行此操作,而且我对 SO 或其他任何在线上建议的其他解决方案没有运气。

这是我的第一个 React 应用程序,所以我不确定我在 React 或 Chart.js 中是否做错了什么?

标签: javascriptreactjschartsdata-visualizationchart.js2

解决方案


根据我的经验,您可以将图表组件和图表容器分开。在图表容器中获取数据并将获取的数据作为道具传递给图表组件,以便更好地组织代码。

您还需要检查是否使用图表组件内的componentWillReceiveProps 生命周期方法更改了道具并相应地更新图表

  1. 创建一个名为 ChartContainer.js 的组件,并将 chartData 作为 props 传递给 ChartComponent
import React, { Component } from 'react';
import ChartComponent from './ChartComponent'

export class ChartContainer extends Component {

  constructor(props) {
    super(props);
    this.state = {
      chartData: []
    }

  componentDidMount() {
    fetch(
        "https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,ETH&tsyms=USD"
      )
        .then(response => {
          return response.json();
        })
        .then(myJson => {
          const bitcoinPrice = myJson.BTC.USD;
          this.setState({ chartData: bitcoinPrice });
          console.log(JSON.stringify(myJson));
        });
  }

  render() {
    const { chartData } = this.state;
    return (
        <ChartComponent chartData={chartData}/ >
    );
  }

}
  1. 创建一个名为 ChartComponent 的组件并获取 chartData 作为 props。还要创建一个称为图表的状态并将图表设置为状态并使用 componentWillReceiveProps 生命周期更新图表以更新图表。
import React, { Component } from 'react';

export class ChartComponent extends Component {

  constructor(props){
    super(props)
    this.state = { chart : null }
  }

  chart = React.createRef();

  componentDidMount(){
    // pass chartData to Chart below as this.props.chartData
    let theChart = new Chart(...)
    // set chart to state
    this.setState({ chart: theChart })
  }

  componentWillReceiveProps(nextProps, nextContext) {
    // update chart according to prop change
      this.state.chart.data.datasets.forEach((dataset) => {
        dataset.data.push(nextProps.chartData);
      });
      this.state.chart.update();
  }

  render(){
    return (
        <canvas id="myChart" ref={this.chart} />
    );
  }

};

推荐阅读