因此,我试图为我的ChartJS应用程序添加使用NextJS的图表。然而,我似乎对它的渲染有问题。我还学习了其他教程和/或文章,但似乎也出现了同样的错误。
我得到的错误是:
Server Error
TypeError: Cannot read properties of null (reading 'useRef')
This error happened while generating the page. Any console logs will be displayed in the terminal window.
我不知道为什么会出现这个错误,因为我没有在代码中使用useRef
钩子。
这是我的root/pages/admin/home.js
代码
import Head from 'next/head'
import Image from 'next/image'
import LineGraph from '../../components/admin/line'
export default function Home() {
return (
<div className="container">
<Head>
<title>Create Next App</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<main>
<LineGraph />
</main>
</div>
)
}
这是我的LineGraph root/components/admin/line.js
代码
import React, { useRef } from 'react';
import { Line } from 'react-chartjs-2';
import Chart from 'chart.js/auto';
const data = {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [
{
label: 'My First dataset',
fill: false,
lineTension: 0.1,
backgroundColor: 'rgba(75,192,192,0.4)',
borderColor: 'rgba(75,192,192,1)',
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: 'rgba(75,192,192,1)',
pointBackgroundColor: '#fff',
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: 'rgba(75,192,192,1)',
pointHoverBorderColor: 'rgba(220,220,220,1)',
pointHoverBorderWidth: 2,
pointRadius: 1,
pointHitRadius: 10,
data: [65, 59, 80, 81, 56, 55, 40]
}
]
};
const LineGraph = () => {
return (
<canvas>
<h2>Line Example</h2>
<Line
id="lineChart"
data={data}
width={400}
height={400}
/>
</canvas>
);
}
export default LineGraph;
如果这个问题是重复的,请放弃这个链接,我再试一试。非常感谢你们的帮助。
发布于 2022-10-12 01:11:22
所以我想出来了。这与软件包版本有关。在我的package.json
文件中,我有以下依赖项:
"dependencies": {
"next": "12.3.1",
"react": "18.2.0",
"react-dom": "18.2.0",
"chart.js": "^2.9.3",
"react-chartjs-2": "^2.9.0"
}
为了使其工作,我必须手动安装带有特定版本的chart.js
和react-chartjs-2
。所以,我的图形终于起作用了,我的package.json
看起来是这样的:
"dependencies": {
"chart.js": "^3.9.1",
"next": "12.3.1",
"react": "18.2.0",
"react-chartjs-2": "^4.3.1",
"react-dom": "18.2.0"
},
发布于 2022-10-11 09:58:21
首先,由于不使用useRef
,所以可以删除导入。
如果将HTML放在canvas
元素中,代码可能会失败,这不是您应该做的事情。
React会自动为您创建画布标签。因此,您应该将画布标记更改为div,甚至是更干净的片段。
const LineGraph = () => {
return (
<>
<h2>Line Example</h2>
<Line
id="lineChart"
data={data}
width={400}
height={400}
/>
</>
);
}
https://stackoverflow.com/questions/74025968
复制相似问题