我正在使用 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/