echarts-for-react中数据发生变化,如何让图表实时更新。

### 点击图表的时候,data数据发生了变化,图表不能实时刷新?

import React from 'react';
import { Card } from 'antd';
import ReactEchartsCore from 'echarts-for-react/lib/core';
import echarts from 'echarts/lib/echarts';
import 'echarts/lib/chart/pie';
echarts.registerTheme('myTheme',{
    backgroundColor: 'rgb(15,55,95)'
});
export default class Bar extends React.Component{
    constructor(props){
        super(props);
        this.state={
            loadingChart:true,
            data:[
                { value: 500, name: 'Android' },
                { value: 200, name: 'IOS' },
                { value: 360, name: 'PC' },
                { value: 100, name: 'Ohter' }
             ]
        }
    }
    onChartClick=()=>{
        const data=this.state.data;
        data.push({
            value:Math.random()*100,
            name:'Other'+Math.random()
        });
        this.setState({
            data
        });
    }
    onChartLegendselectchanged = () => {
        console.log(2)
    }

    // 方法必须放在上面,不然找不到对应的方法
    onEvents = {
        'click': this.onChartClick,
        'legendselectchanged': this.onChartLegendselectchanged
    }

    // 获取配置
    getOption=()=>{
            const option = {
                title:{
                    text:'ECharts 数据统计'
                }, 
                lengend:{},        
                series:[{
                    name:'访问量',
                    type:'pie',    
                    radius:'60%', 
                    data:this.state.data
                }]
            };
            return option;
    }

    // charts loadReady后的回调 模拟回调
    onChartReadyCallback=()=>{
        setTimeout(()=>{
            this.setState({
                loadingChart: false
            });
        } ,2000);
    }

  render(){
    return (
      <div>
        <p>{JSON.stringify(this.state.data)}</p>
        <Card title="饼图">
          <ReactEchartsCore 
            echarts={echarts}
            style={{ height: '500px' }}
            className='noneClass' 
            theme='light'
            onChartReady={this.onChartReadyCallback}
            option={this.getOption()}
            showLoading={this.state.loadingChart}
            onEvents={this.onEvents}
            lazyUpdate={(this.getOption(),false)} 
            >
        </ReactEchartsCore>
        </Card>
    </div>)
  }
}
阅读 13.8k
2 个回答

需要用到echarts的 setOption
我是用函数组件写的

<ReactEcharts
    ref={(e) => { refs.echartsReact = e; }}
    className="graph"
    option={options}
    notMerge={false}
    lazyUpdate={true}
    style={style || {height:'484px',width:'685px'}}
/>

每当有新数据过来,直接refs.echartsReact.getEchartsInstance().setOption(options); 就行了

data变了,但是echarts里的option没有重新计算,所以需要重新调用this.getOption()来计算新的数据,可以把getOption()放在render里

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题