react中定时刷新echarts图表

13 篇文章 2 订阅
6 篇文章 0 订阅

实现效果

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图表

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值