Dynamically update Highcharts chart in react

梦想的初衷 提交于 2020-06-12 06:30:30

问题


I am using highcharts-react-official in react-redux to create a drilldown chart.

However when I click on a bar to drilldown, I also update some props which causes the component to re-render - which seems to prevent the drilldown event.

I kind of gathered from Change series data dynamically in react-highcharts without re-render of the chart that I should use shouldComponentUpdate and getChart() to prevent re-render and instead dynamically update the data.

My issue is that getChart() doesn't seem to work for the official highcharts react package. I'm getting Uncaught TypeError: this.refs.chart.getChart is not a function

Is there an alternative I'm meant to be using to get and dynamically update the chart? Or some examples that I could look at?

Just including render and shouldComponentUpdate parts here:

shouldComponentUpdate(nextProps, nextState) {
    let chart = this.refs.chart.getChart();
    //dynamically update data using nextProps
    return false;
}

render () {

    const options = {
        chart: {
            type: 'column',
            height: 300,
            events: {
                drillup: (e) => {this.drilledUp(e)}
            }
        },
        plotOptions: {
            series: {
                events:{
                      click: (e) => {this.categoryClicked(e)}
                }
            }
        },
        xAxis: {type: "category"},
        yAxis: {title: {text: 'Amount Spent ($)'}},
        series: [{
            name: 'weekly spending',
            showInLegend: false,
            data: this.props.transactionChartData.series_data,
            cursor: 'pointer',
            events: {
                click: (e)=> {this.weekSelected(e)}
            }
        }],
        drilldown: {
            series: this.props.transactionChartData.drilldown_data

        }
    };
    return (
        <HighchartsReact
        highcharts={Highcharts}
        options={options}
        ref="chart"
        />
    )
}

回答1:


In highcharts-react-official v2.0.0 has been added allowChartUpdate option, which should work great in your case. By using this option you can block updating the chart with updating the component:

categoryClicked() {
  this.allowChartUpdate = false;
  this.setState({
    ...
  });
}

...

  <HighchartsReact
    ref={"chartComponent"}
    allowChartUpdate={this.allowChartUpdate}
    highcharts={Highcharts}
    options={...}
  />

Moreover, to get the chart instance use refs:

componentDidMount(){
  const chart = this.refs.chartComponent.chart;
}

Live demo: https://codesandbox.io/s/98nl4pp5r4



来源:https://stackoverflow.com/questions/53773491/dynamically-update-highcharts-chart-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!