如何从内部更新Highchart对组件做出反应?

时间:2018-05-05 02:33:33

标签: reactjs highcharts

我正在使用react 16.3,其中componentWillUpdate已弃用(严格模式)。我们在Highcharts周围有一个反应包装器,用于更新在渲染之前运行的highchart中的componentWillUpdate

但是现在在输入highchartoptions道具更新时的反应16.3中,似乎无法在调用Highchart.update之前调用render()。它建议使用componentDidUpdate但仅在render()之后调用它,它似乎根本不起作用。任何建议都会有所帮助。

此处的代码段:

export class HighchartReactWrapper extends React.Component {
  constructor(props) {
    super(props);

    // We maintain the user provided options being used by highchart as state
    // inorder to check if chart update is needed.
    this.state = { highChartOptions: this.props.options };
    this.onChartRendered = this.onChartRendered.bind(this);
  }

  componentDidMount() {
    // Create chart
    this.chart = new Highcharts.Chart(this.container, this.state.highChartOptions, this.onChartRendered);
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.options !== prevState.options) {
      return { highChartOptions: nextProps.options };
    }
  }

  componentDidUpdate() {
    this.chart.update(this.state.highChartOptions, false, true); <---- Doesn't work
  }

  onChartRendered() {
    // Callbacks..
    if (this.props.onChartRenderedCallback !== undefined) {
      this.props.onChartRenderedCallback();
    }
  }

  componentWillUnmount() {
    // Destroy chart
    this.chart.destroy()
  }

  render() {
    return (
      <div className="react-highchart-wrapper">
        <div id={container => this.container = container} />
      </div>
    );
  }
}

HighchartReactWrapper.propTypes = {
  /**
   * Chart options to be used in Highcharts library.
   */
  options: PropTypes.object.isRequired,
  onChartRenderedCallback: PropTypes.func
};

HighchartReactWrapper.defaultProps = {
  options: undefined,
  onChartRenderedCallback: undefined
};

1 个答案:

答案 0 :(得分:1)

您可以使用在组件重新渲染之前调用的shouldComponentUpdate(nextProps, nextState)