我的代码使用ultimatejs:tracker-react和react-highcharts来使用从Mongodb集合中提取的实时数据绘制图表。为了简单起见,启用了autopublish包。
问题:在设置了高级图表的初始数据系列后,chart.series[0].setData([5,4,3,2,1])会更新该系列,但是新的数据不会绘制在图表上。图表仍然显示最初的3点高图集是用初始化的。
如何在图表上绘制新的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>
)
}
}发布于 2016-12-01 10:48:48
我想我解决了这个问题。这是用于呈现图表的包:
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语句如果为falsechart1。但是它并没有停止,React继续呈现,ReactHighCharts用旧的配置创建了一个新的图表实例(chart2),并将它放在这个屏幕上。这个chart2取代了chart1,所以您永远看不到更新的图表。https://stackoverflow.com/questions/40903083
复制相似问题