我有一个Chart组件,该组件从两个来源获取图表数据: 第一个每分钟提供历史烛台数据。 第二个提供当前烛台的实时数据。 两者都通过setState更新系列对象。
问题在于,只有第一个来源会更新图表。
我希望在第二个来源发送当前烛台数据并更新状态之后,最后一个烛台在图表上更新,但不会更新。它不动。尽管渲染是在两次更新之后(从第一个和第二个源)触发的,但我可以在控制台输出中查找。我还可以在日志中看到,在进行两种更新后,this.state.series的格式完全相同。
这是我的图表组件的代码:
import React from "react";
import Chart from "react-apexcharts";
import moment from "moment";
export default class ChartComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
series: [{data:[]}],
options: {chart: {id: "basic-bar"}}
}
}
componentDidMount() {
this.startEventSource();
}
startEventSource = ()=> {
this.eventSource = new EventSource(`http://localhost:9000/candleStream`);
this.eventSource.onmessage = e => this.updateChart(JSON.parse(e.data), "Minute");
this.eventSource2 = new EventSource(`http://localhost:9000/priceStream`);
this.eventSource2.onmessage = e => this.updatePrice(JSON.parse(e.data))
}
updatePrice = (newCandleData) => {
var candleData = newCandleData.split(";");
let momentWithoutSeconds = moment(parseInt(candleData[4])).seconds(0).milliseconds(0).valueOf();
let candle = [momentWithoutSeconds, parseFloat(candleData[0]), parseFloat(candleData[1]), parseFloat(candleData[2]), parseFloat(candleData[3]) ]
let newCandleList = this.state.series[0].data;
if(newCandleList.filter(c => c[0] == momentWithoutSeconds).length == 0) {
newCandleList.push(candle);
} else {
newCandleList[newCandleList.length - 1] = candle;
}
this.updateChart([{data:newCandleList}], "Price");
}
updateChart = (data, source) => {
this.setState({series: data}, console.log(source, this.state.series));
}
render() {
console.log("render triggered!")
return (
<div className="app">
<div className="row">
<div className="mixed-chart">
<Chart
options={this.state.options}
series={this.state.series}
type="candlestick"
width="1000"
/>
</div>
</div>
</div>
);
}
}
这是一个示例控制台输出,其中系列的结构可见:
有人可以告诉我我在做什么错吗?
编辑:在调整浏览器窗口大小时,图表会更新。
答案 0 :(得分:1)
我今天在处理图表时遇到了类似的问题。我的情况是通过在render()中将状态值设置为常量来解决的。不知道为什么要这样解决它。
render() {
const { options, series } = this.state;
console.log("render triggered!")
return (
<div className="app">
<div className="row">
<div className="mixed-chart">
<Chart
options={options}
series={series}
type="candlestick"
width="1000"
/>
</div>
</div>
</div>
);
}