問題現象
在 React 項目中使用 ECharts 時,控制枱報錯:
series not exists. Legend data should be same with series name or data name
但已確認 legend.data 與 series.name 完全匹配,代碼邏輯看似正確。
問題根源
未正確註冊 ECharts 圖表組件。自 ECharts 5 起,官方採用按需引入(tree-shaking)的模塊化設計,需顯式註冊圖表類型。
解決方案
1. 正確引入圖表組件
// 正確方式:顯式引入並註冊柱狀圖
import * as echarts from 'echarts/core';
import { BarChart } from 'echarts/charts';
import { GridComponent, LegendComponent } from 'echarts/components';
// 註冊必要組件
echarts.use([BarChart, GridComponent, LegendComponent]);
關鍵注意事項
-
組件註冊順序
// 錯誤:遺漏 BarChart 註冊 echarts.use([GridComponent]); // ❌ 缺少圖表類型 // 正確:註冊所有依賴組件 echarts.use([BarChart, GridComponent, LegendComponent]); // ✅ -
按需引入的優勢
- 減少打包體積(未使用的組件不會被打包)
- 提升初始化速度
-
常見圖表類型註冊
// 折線圖 import { LineChart } from 'echarts/charts'; // 餅圖 import { PieChart } from 'echarts/charts'; // 地圖 import { MapChart } from 'echarts/charts';
錯誤排查清單
- 檢查
series.type是否與註冊的圖表類型匹配 - 確認
echarts.use()包含所有依賴組件 - 驗證
series.name與legend.data完全一致(包括大小寫) - 確保
echarts版本 ≥ 5.0.0
總結
該錯誤的本質是 ECharts 無法識別未註冊的圖表類型。通過顯式註冊組件並保持 name 字段的一致性,即可徹底解決問題。按需引入的設計雖然增加了初始化步驟,但顯著提升了大型項目的性能表現。