2

我的代码使用ultimatejs:tracker-reactreact-highcharts使用从 Mongodb 集合中提取的实时数据绘制图表。为简单起见,autopublish启用了包。

问题:为 Highcharts 设置初始数据系列后,chart.series[0].setData([5,4,3,2,1])更新系列但未在图表上绘制新数据。图表仍然显示初始化 Highcharts 的初始 3 点。

我们如何才能series在 highcharts 图表上绘制新值?

import React, { Component, PropTypes } from 'react';
import ReactDOM from 'react-dom';
import TrackerReact from 'meteor/ultimatejs:tracker-react';
import ReactHighcharts from 'react-highcharts';

import { Pressure } from '../api/pressure.js';


export class PressureChart extends TrackerReact(Component) {

    // Returns data in the Highcharts series format
    seriesData() {
        const result = Pressure.find().fetch();
        pressure = _.pluck(result, 'pressure');
        pressure = pressure.map(p => Number(p))
        time = _.pluck(result, 'timestamp');
        series = _.zip(time, pressure);
        return pressure
    }

    updateChart() {
        let chart = this.refs.chart.getChart()
        console.log(chart.series[0].data)       // Echos out an array of 3 elements
        chart.series[0].setData([5,4,3,2,1])    // Tests using this array, instead of array pulled from Collection
        console.log(chart.series[0].data)       // Echos out an array of 5 elements
    }

    render() {
        const config = {
            series: [{
                data: [1,2,3]
            }]
        };

        if(this.seriesData().length){
            this.updateChart()
        }

        return (
            <ReactHighcharts config={config} ref="chart"></ReactHighcharts>
        )
    }
}
4

1 回答 1

0

我想我找出问题所在。这是这个包用来渲染图表:

renderChart: function (config){
  if (!config) {
    throw new Error('Config must be specified for the ' + displayName + ' component');
  }
  let chartConfig = config.chart;
  this.chart = new Highcharts[chartType]({
    ...config,
    chart: {
      ...chartConfig,
      renderTo: this.refs.chart
    }
  }, this.props.callback);

  if (!this.props.neverReflow) {
    win.requestAnimationFrame && requestAnimationFrame(()=>{
      this.chart && this.chart.options && this.chart.reflow();
    });
  }
},

shouldComponentUpdate(nextProps) {
  if (nextProps.neverReflow || (nextProps.isPureConfig && this.props.config === nextProps.config)) {
    return true;
  }
  this.renderChart(nextProps.config);
  return false;
},

getChart: function (){
  if (!this.chart) {
    throw new Error('getChart() should not be called before the component is mounted');
  }
  return this.chart;
},

componentDidMount: function (){
  this.renderChart(this.props.config);
},

参考:https ://github.com/kirjs/react-highcharts/blob/master/src/chartsFactory.jsx#L22-L59

如您所见,每次需要绘制/更新图表时,包都会创建一个新图表并将其放置在屏幕上。在您的代码中,您在渲染函数中使用更新图表函数,所以会发生以下情况:

  • 首次渲染:调用 this 的图表chart1正常渲染,因为 if 语句 if false
  • 第二次渲染:如果为真,则执行内部的代码,chart1并更新。但它并不止于此,React 继续渲染,ReactHighChartschart2使用旧配置创建一个新的图表实例 ( ) 并将其放置在此屏幕上。这chart2将替换chart1,因此您永远不会看到更新的图表。
于 2016-12-01T10:48:48.927 回答