在componentWillReceiveProps期间添加系列不起作用

问题描述 投票:0回答:1

我已经在这一段时间了,我很难过。我有一个react组件,它应该在收到道具时添加一个新系列,但是chart.getChart().addSeries({ data: [1, 2, 3, 4] })没有在我的图表中显示新系列。但是,我还在onClick添加了一个新系列的组件中添加了一个按钮,这确实有用......下面是我的代码:

const config = {
  title: {
    text: 'Hello, World!'
  },
  xAxis: {
    categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  },
  series: [{
    data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
  }]
}
@autobind class SampleChart extends Component {
  componentWillReceiveProps({ data }) {
    if(data.length > 0) {
      this.chart.getChart().addSeries({data: [39.9, 81.5, 116.4, 229.2, 124.0, 174.0, 235.6, 138.5, 116.4, 94.1, 195.6, 54.4]}, false)
      this.chart.getChart().redraw()
    }
  }

  addSeries() {
    this.chart.getChart().addSeries({data: [39.9, 81.5, 116.4, 229.2, 124.0, 174.0, 235.6, 138.5, 116.4, 94.1, 195.6, 54.4]}, false)
    this.chart.getChart().redraw()
  }

render() {
    return(
      <div>
        <ReactHighcharts ref={(ref) => this.chart = ref} config={config} />
        <button onClick={this.addSeries}>add series</button>
      </div>
    )
  }
}
export default SampleChart

顺便说一句,我确实通过了if(data.length > 0)语句,每当我向组件传递一组新的道具时,我就会遇到这个问题。所以这不是一个组件安装问题(至少我认为不是)。有关为什么会发生这种情况的任何想法?

javascript reactjs highcharts react-highcharts react-component
1个回答
0
投票

我弄清楚发生了什么。对于后代,这里是你如何解决它:

基本上错误的是componentsWillReceiveProps()触发渲染,我认为this.chart.getChart().redraw()没有时间重绘渲染。所以我补充说:

componentShouldUpdate() {
  return false
}

这使它工作!由于组件不呈现,图表只是重绘。但是,让整个考验变得极为困惑的是,如果你setData(),即使没有componentShouldUpdate(),图表也会重新绘制和更新。

Here你可以看到一个例子,当setData()存在时和不存在时,这两种情况如何反应(addSeries()componehtShouldUpdate())。

© www.soinside.com 2019 - 2024. All rights reserved.