如何使用 API 数据在 React 和 Chart.js 应用程序中正确更新图表

How to properly update chart in React & Chart.js app using API data

我正在从 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 中做错了什么?

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

您还需要检查图表组件中的 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 作为道具。同时创建一个名为 chart 的状态并将图表设置为该状态并使用 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} />
    );
  }

};

当 props 改变时,ChartComponent 不会刷新。要使其工作,请使用 redraw={true}

<ChartComponent type={chartType} {...someConfig} redraw={true}/>