Lỗi "Có một phiên bản biểu đồ đã được khởi tạo trên dom" trong React + ECharts

Khi sử dụng thư viện ECharts trong React, lỗi "There is a chart instance already initialized on the dom" thường xảy ra do việc khởi tạo biểu đồ trùng lặp trên cùng một phần tử DOM. Giải pháp được đề xuất như sau:

Cấu hình lấy từ props
const [biểu_đồ, setBiểu_Đồ] = useState(null);
const { tùy_chọn_cấu_hình } = props;

useEffect(() => {
  if (JSON.stringify(tùy_chọn_cấu_hình) !== "{}") {  
    if (biểu_đồ) {
      cập_nhật_biểu_đồ();
    }
  }
}, [tùy_chọn_cấu_hình]);

useEffect(() => {
  const instance = echarts.init(dom.current);
  setBiểu_Đồ(instance);
  cập_nhật_biểu_đồ();
  xử_lý_thay_đổi_kích_thước();
  
  return () => {
    if (biểu_đồ) {
      biểu_đồ.dispose(dom.current);
      biểu_đồ.clear();
      window.resize = null;
    }
    window.removeEventListener("resize", xử_lý_thay_đổi_kích_thước);
  };
}, []);
Phiên bản sửa lỗi
import React, { useEffect, useState, memo, createRef } from "react";
import { merge, debounce } from "lodash";
import * as echarts from "echarts";

function Component(props) {
const dom = createRef();
const [biểu_đồ, setBiểu_Đồ] = useState(null);
const { tùy_chọn_cấu_hình } = props;

useEffect(() => {
if (JSON.stringify(tùy_chọn_cấu_hình) !== "{}") {
if (biểu_đồ) {
cập_nhật_biểu_đồ();
}
}
}, [tùy_chọn_cấu_hình]);

useEffect(() => {
const instance = echarts.init(dom.current);
setBiểu_Đồ(instance);
cập_nhật_biểu_đồ();
xử_lý_thay_đổi_kích_thước();

return () => {
if (biểu_đồ) {
biểu_đồ.dispose(dom.current);
biểu_đồ.clear();
window.resize = null;
}
window.removeEventListener("resize", xử_lý_thay_đổi_kích_thước);
};
}, []);

const cấu_hình_cơ_bản = {
grid: {
top: 30,
right: 10,
left: 40,
bottom: 10,
containLabel: true,
},
tooltip: {
trigger: "item",
},
legend: {
top: "5%",
left: "center",
},
series: [],
};

const tạo_tùy_chọn = () => {
if (!tùy_chọn_cấu_hình) return;
return merge({}, cấu_hình_cơ_bản, tùy_chọn_cấu_hình);
};

const cập_nhật_biểu_đồ = () => {
if (!biểu_đồ) return;
const fullOption = tạo_tùy_chọn();
biểu_đồ.setOption(fullOption, true);
};

const xử_lý_thay_đổi_kích_thước = () => {
const resizeHandler = debounce(() => {
if (biểu_đồ) {
biểu_đồ.resize();
}
}, 100);
window.addEventListener("resize", resizeHandler);
};

return ;
}
export default memo(Component);

Thẻ: react echarts JavaScript React Hooks DOM Manipulation

Đăng vào ngày 29 tháng 8 lúc 07:34