【问题标题】:Adding Series during componentWillReceiveProps does not work在 componentWillReceiveProps 期间添加 Series 不起作用
【发布时间】:2018-03-01 17:37:22
【问题描述】:

我在这方面已经有一段时间了,我很困惑。我有一个反应组件,它应该在收到道具时添加一个新系列,但是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 &gt; 0) 语句,每当我将一组新的道具传递给我的组件时,我都会遇到这个问题。所以这不是组件安装问题(至少我认为不是)。 关于为什么会发生这种情况的任何想法?

【问题讨论】:

    标签: javascript reactjs highcharts react-highcharts react-component


    【解决方案1】:

    我知道发生了什么。对于后代,这是您解决它的方法:

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

    componentShouldUpdate() {
      return false
    }
    

    这使它工作!由于组件不渲染,图表只是重绘。然而,让整个考验变得超级混乱的是,如果你setData(),即使没有componentShouldUpdate(),图表也会重新绘制和更新。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-03
      • 2020-03-05
      • 2016-08-20
      • 1970-01-01
      • 2012-04-29
      • 2013-09-15
      • 1970-01-01
      相关资源
      最近更新 更多