解决react+echarts的项目中There is a chart instance already initialized on the dom警告

转载来自消除There is a chart instance already initialized on the dom. React中使用echarts - 代码先锋网

使用echarts.getInstanceByDom获取之前可能创建过的实例,如果有则继续使用这个实例,否则创建

import * as echarts from 'echarts';
import { useEffect } from 'react'

function EchartsCom(props: any) {
    let chartDom: any
    let myCharts: any
    const getEchartsData = (objs: any) => { //获取echarts中的数据
        return {
            xAxis: {
                type: 'category',
                data: objs.xAxis
            },
            yAxis: {
                type: 'value'
            },
            series: [
                {
                    data: objs.series,
                    type: 'line'
                }
            ]
        }

    }
    // 监听父组件中传递的数据变化
    useEffect(() => {
        if (props?.objs) {
            chartDom = document.getElementById('main');
            myCharts = echarts.getInstanceByDom(chartDom); //获取之前的echarts的实例
            if (!myCharts) { //没有就初始化echarts实例
                myCharts = echarts.init(chartDom);
            }
            myCharts.setOption(getEchartsData(props?.objs)) //调用echarts
        }
    }, [props.objs])

    return (
        <div id="main" style={{ width: 100 + '%', height: '340px' }}></div>
    )
}

export default EchartsCom