【问题标题】:Chartjs in Reactjs - how can I update data dynamically?Reactjs 中的 Chartjs - 如何动态更新数据?
【发布时间】:2019-02-24 17:47:39
【问题描述】:

这是我第一次使用 Chartjs,而且我也不是 React 方面的专家。我正在尝试实现一个条形图,该条形图应该可能从 CONST 中获取数据,这些 CONST 是使用用户输入提供的数字的计算器。这就是图表现在的工作方式。 data 中的值是硬编码的,我不知道如何使它们动态化。

  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"/>

【问题讨论】:

  • 据我所知,您是否只加载了一次 chartData。 ComponentWillMount 只被调用一次。您可以在用户更新输入字段时使用 setstate,然后调用 getChartData 函数。
  • 你在谈论“数据中的值是硬编码的,我不知道如何使它们动态化”。你说的是数据:[617594, 181045,], ?
  • 这些动态数据从何而来?在 AJAX 调用中?如果是这样,我建议在此页面顶部的搜索框中搜索“AJAX ReactJS”。看起来很多人都问过这个话题,并得到了很好的答案。祝你好运!
  • @StephanHovius 是的,这就是我的意思,如果我说得不对,请见谅。
  • @AndyTaton 不,我没有使用 Ajax,该应用程序的基础是它根据用户输入的数字计算投资回报。之后,它比较两个值并用条形图说明。

标签: reactjs chart.js state


【解决方案1】:

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

停止使用状态

尝试将数组作为参数传递给你的函数,然后将参数直接发送给图表数据对象,然后直接从函数内部初始化图表(在这种情况下我避免使用React state因为它有一个延迟,并且 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)
     }
}

在重新创建图表之前,您还需要“destroy()”图表。希望这会有所帮助!

【讨论】:

  • 如何动态添加多个数据集有什么想法吗? datasets: [{ label: 'Sentiment', data: [data], }] 我应该动态获取标签和数据?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-10
  • 2013-06-25
  • 1970-01-01
  • 1970-01-01
  • 2021-03-15
相关资源
最近更新 更多