在Gatsby中使用react-chartjs-2出现“无法读取未定义属性”错误
在Gatsby中使用react-chartjs-2报错的修复方案
问题描述
在Gatsby项目中集成react-chartjs-2时,编写测试代码后出现以下错误:
Uncaught TypeError: Cannot read properties of undefined (reading 'prototype') at TypedRegistry.isForType (chart.esm.js:4756:1) at Registry._getRegistryForType (chart.esm.js:4899:1) at eval (chart.esm.js:4879:1) at Array.forEach (<anonymous>) at Registry._each (chart.esm.js:4878:1) at Registry.add (chart.esm.js:4836:1) at Chart.value [as register] (chart.esm.js:6169:1) at eval (webpack-internal:///./src/pages/elements/artists.jsx:17:45) at ./src/pages/elements/artists.jsx (component---src-pages-index-js.js:62:1) at options.factory (commons.js:3711:31)
测试代码如下:
import React from "react" import { Chart, Arclement, Tooltip, Legend } from 'chart.js' import { Pie } from 'react-chartjs-2' const data = { labels: ['Taxation', 'Materials', 'Profit', 'Expenses', 'Wages'], datasets: [ { label: 'Tax bill', data: [25, 20, 8, 12, 34], }, ], }; const PieChart = () => { return ( <div style={{ width: '750px' }}> <Pie data={data} /> </div> ); }; const Artists = (props) => { let artistChart = getArtistChart(orderArtists(props.stats)); return ( <div id="statsCard"> <PieChart /> </div> ) }
错误原因及修复方法
1. 组件名称拼写错误
代码中导入的Arclement是拼写错误,正确的组件名应为ArcElement,这是导致报错的直接原因。
2. 未正确注册Chart.js组件
新版Chart.js(v4+)需要手动注册核心组件才能使用,react-chartjs-2 v4+依赖此版本,因此需要在代码中完成组件注册。
修正后的代码
import React from "react" // 修正拼写错误,并导入正确的组件 import { Chart, ArcElement, Tooltip, Legend } from 'chart.js' import { Pie } from 'react-chartjs-2' // 注册必要的Chart.js组件 Chart.register(ArcElement, Tooltip, Legend) const data = { labels: ['Taxation', 'Materials', 'Profit', 'Expenses', 'Wages'], datasets: [ { label: 'Tax bill', data: [25, 20, 8, 12, 34], // 添加颜色配置,确保图表正常显示 backgroundColor: [ '#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF' ] }, ], }; const PieChart = () => { return ( <div style={{ width: '750px' }}> <Pie data={data} /> </div> ); }; const Artists = (props) => { // 需确保getArtistChart和orderArtists函数已提前定义 let artistChart = getArtistChart(orderArtists(props.stats)); return ( <div id="statsCard"> <PieChart /> </div> ) }
额外注意事项
- 确保
react-chartjs-2和chart.js版本兼容:建议使用react-chartjs-2@^4.0.0搭配chart.js@^4.0.0 - 代码中
getArtistChart和orderArtists函数需要提前定义,否则会引发新的未定义错误
内容的提问来源于stack exchange,提问作者Domingo Blavriano
相关产品推荐
相关产品推荐

