0

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

4

1 回答 1

0

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

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

componentShouldUpdate() {
  return false
}

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

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

于 2018-03-01T19:45:48.813 回答