在 Gatsby 中使用 react-chartjs-2 会让我在其组件中出现"cannot read properties of undefined"错误



我正试图在盖茨比项目中使用react-chartjs-2。我跟随这个网站写下了第一个测试,看看它是否有效。我的代码是:

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>
)
}

我得到以下错误:

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)

这是由盖茨比内部使用chartjs的错误方式引起的,还是可以按原样修复?

看起来像是SSR(Sserver-SideRendering(问题,所以当代码在Node服务器中编译时会失败。

我建议使用React.Suspenseloadable组件将依赖项直接动态导入客户端,将代码保留为:

import React from "react"
import { Chart, Arclement, Tooltip, Legend } from 'chart.js'
import loadable from '@loadable/component'
const { Pie } = loadable(() => import('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>
)
}

或使用React.Suspense:

const { Pie } = React.lazy(() => import("react-chartjs-2"));
import React from "react"
const data = {
labels: ["Taxation", "Materials", "Profit", "Expenses", "Wages"],
datasets: [
{
label: "Tax bill",
data: [25, 20, 8, 12, 34],
},
],
};
function MyComponent() {
return (
<React.Suspense fallback={"Loading"}>
<div>
<Pie data={data} />
</div>
</React.Suspense>
);
}

注意:如果不需要,请移除fallback

另一种替代解决方案是通过在gatsby-node.js:中添加以下内容,为react-chartjs-2依赖项添加null加载程序

exports.onCreateWebpackConfig = ({ stage, loaders, actions }) => {
if (stage === "build-html" || stage === "develop-html") {
actions.setWebpackConfig({
module: {
rules: [
{
test: /react-chartjs-2/,
use: loaders.null(),
},
],
},
})
}
}

修改自:https://www.gatsbyjs.com/docs/debugging-html-builds/.在本文档中,您还可以找到有关可加载组件的更多信息

在上面的代码段中,test是一个正则表达式(这就是为什么它位于斜杠/之间(,它应该与有问题模块的node_modules中的文件夹名称相匹配。

相关内容

  • 没有找到相关文章

最新更新