reactjs - 如何从组件内部更新 Highchart?

标签 reactjs highcharts

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

但现在在 React 16.3 中,当输入 highchartoptions 属性更新时,似乎无法在 render() 之前调用 Highchart.update > 被调用。建议使用 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
};

最佳答案

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

关于reactjs - 如何从组件内部更新 Highchart?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50185157/

相关文章:

javascript - ReactJS 组件在 className 更改时意外重新加载

reactjs - 我如何使用 Nextjs 将我的 URL 与应用程序状态同步

javascript - 如何设置 Highcharts 中文本的宽度限制?

jquery - 如何从 HighCharts 图例中删除色样而不影响列?

javascript - 在 HighStocks Navigator 中隐藏系列数据的简单方法是什么

javascript - react : custom select element

javascript - 在 css 中通过 Eslint 提交时出现错误

javascript - Highcharts 中存在多个系列数据,但第二条线图显示被压扁?

javascript - 在单个页面上处理两个 ajax 调用以将数据拉入另一个页面上的 Highcharts

javascript - 使用 React 删除 Firebase 中的项目,重新渲染返回项目未定义