我的代码使用ultimatejs:tracker-react
和react-highcharts
使用从Mongodb集合中提取的实时数据绘制图表。为简单起见,启用了autopublish
包。
问题:为Highcharts设置初始数据系列后,chart.series[0].setData([5,4,3,2,1])
会更新系列,但新数据不会在图表上绘制。图表仍显示最初的3点Highcharts已初始化为。
我们如何才能在高价图表上绘制新的series
值?
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>
)
}
}
答案 0 :(得分: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
如您所见,每次需要绘制/更新图表时,包都会创建一个新图表并将其放在屏幕上。在您的代码中,您在渲染功能中使用更新图表功能,因此会发生以下情况:
chart1
,正常呈现,因为if语句为false chart1
更新。但它并不止于此,React继续渲染,ReactHighCharts使用旧配置创建一个新的图表实例(chart2
)并将其放在此屏幕上。此chart2
会替换chart1
,因此您永远不会看到更新的图表。