实现效果
Ant Design结合React定时获取数据并刷新echarts图表,实现效果如下:
关键问题
- 在componentWillMount中设置定时器定时获取数值,在componentWillUnmount中删除定时器
- 使用echarts-for-react构建echarts图表,数据刷新时填充新的数值到echarts option中,随后获取echarts图表dom并手动设置新的echarts option,才能实现图表的刷新
实现过程
代码和注释如下:
import React, { PureComponent } from 'react';
import ReactEcharts from 'echarts-for-react';
constructor(props) {
super(props);
this.option = {...} // echarts options,见官网
}
componentWillMount() {
const { func, interval, robin } = this.props;
const getMetersStatus = () => {
func().then(data => {
// 更新echarts options,填充新获取的数值到options中
const option = this.handleOption(data);
this.setState({
status: data,
});
// 手动更新echarts options,setOption方法触发echarts图表更新
// 否则state数值改变,但是echarts图表不变
// echarts_react是设置的echarts图表dom名称,见后面
if (this.echarts_react) {
this.echarts_react.getEchartsInstance().setOption(option, true);
}
});
};
getMetersStatus();
if (robin) {
// 设置定时器
this.interval = setInterval(getMetersStatus, interval);
}
}
componentWillUnmount() {
if (this.interval) {
// 卸载定时器
clearInterval(this.interval);
}
}
// 更新echarts option方法
handleOption = data => {
const { option } = this;
option.legend.data = [];
option.series[0].data = [];
for (let i = 0; i < data.length; i += 1) {
const obj = {};
obj.value = data[i].value;
obj.name = `${data[i].name}: ${data[i].value}`;
option.series[0].data.push(obj);
option.legend.data.push(`${data[i].name}: ${data[i].value}`);
}
return option;
};
...
render() {
const { style } = this.props;
const { status } = this.state;
return status.length === 0 ? (
<Loading top={40} />
) : (
// 给ReactEcharts加上ref,也就是dom名称是echarts_react
<ReactEcharts
ref={e => {
this.echarts_react = e;
}}
option={this.option}
theme="light"
style={style}
notMerge
/>
);
}
相关思考
也可以在父组件生命周期函数中获取数值,作为属性传递给子组件,在子组件中执行setOption方法,同样可以更新echarts图表