React.js中的Chart.js-如何动态更新数据?

时间:2018-09-20 12:00:13

标签: reactjs chart.js state

这是我第一次使用Chartjs,而且我也不是React的专业人士。我正在尝试实现一个条形图,该条形图应该使用用户输入提供的数字从计算程序的CONST中获取其数据。图表现在就是这样工作的。数据中的值是经过编码的,我不知道如何使它们动态化。

  constructor(props) {
    super(props);

    this.state = {
            chartData:{},
      visitors: "",
      conversion: 4,
      value: "",

            smileeconversion: "",
            smileevalue: "",

            swcost: "",
            labourcost: "",
            roi: ""
    };
  }

    componentWillMount(){
    this.getChartData();
  }

      getChartData(){
    // Ajax calls here
    this.setState({
      chartData:{
        labels: ['Before', 'After'],
        datasets:[
          {
            label:'Population',
            data:[
              617594,
              181045,
            ],
            backgroundColor:[
              'rgba(255, 99, 132, 0.6)',
              'rgba(54, 162, 235, 0.6)',
              'rgba(255, 206, 86, 0.6)',
              'rgba(75, 192, 192, 0.6)',
              'rgba(153, 102, 255, 0.6)',
              'rgba(255, 159, 64, 0.6)',
              'rgba(255, 99, 132, 0.6)'
            ]
          }
        ]
      }
    });
  }

这是图表组件:

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

class Chart extends Component{
  constructor(props){
    super(props);
    this.state = {
      chartData:props.chartData

    }
  }

  static defaultProps = {
    displayTitle:true,
    displayLegend: true,
    legendPosition:'right',
    location:'City'
  }

  render(){
    return (
      <div className="chart">
        <Bar
          data={this.state.chartData}
          options={{
            title:{
              display:this.props.displayTitle,
              text:'Return of investments',
              fontSize:25
            },
            legend:{
              display:this.props.displayLegend,
              position:this.props.legendPosition
            }
          }}
        />
      </div>
    )
  }
}

export default Chart;

及其父组件:

 <Chart chartData={this.state.chartData} location="Massachusetts" legendPosition="bottom"/>

1 个答案:

答案 0 :(得分:1)

这是一种略有不同的方法,但是我认为它比您正在做的事情简单:

停止使用状态

尝试将数组作为参数传递到函数中,然后将参数直接发送到统计图数据对象,然后直接从函数内的初始化统计图(在这种情况下,我避免使用React状态因为它存在滞后,因此Chart.js希望立即启动)。

这是一个小例子:

let barChart;
let newLabels = ["Label1", "Label2", "Label3"];
let newData = ["Data1", "Data2", "Data3"];

createBarChart = (labels, data) => {

    let ctx = "bar_l1_chart";

    barChart = new Chart(ctx, {
        type: 'horizontalBar',
        data: {
            labels: [labels],
            datasets: [{
                label: 'Sentiment',
                data: [data],
            }]
        },
    });
};
this.createBarChart(newLabels, newData);

现在,您只需更新“ newLabels”或“ newData”数组,然后重新调用该函数即可。一个好的方法是使用React状态管理器,例如:

componentWillRecieveProps(newProps){
     if(newProps.labels && newProps.data) {
          if(barChart){barChart.destroy()};
          this.createBarChart(newProps.labels, newProps.data)
     }
}

您还需要在重新创建图表之前对其进行“破坏()”。希望这会有所帮助!