【发布时间】:2020-08-11 07:47:12
【问题描述】:
我正在使用 TypeScript 和 Next.js 开展一个项目。到目前为止,该网站非常简单,仅包含几页,在我的项目上运行 next build 时,我不断收到以下错误:
Automatically optimizing pages .
Error occurred prerendering page "/404". Read more: https://err.sh/next.js/prerender-error:
Error: Error for page /_error: pages with `getServerSideProps` can not be exported. See more info here: https://err.sh/next.js/gssp-export
我没有自定义 404 页面,因为我希望它由 _error.tsx 页面处理,因为我有用于尾部斜杠的服务器端重定向。这在开发环境中运行时有效,但在我尝试构建它时会死机。
显然_error.tsx 有getServerSideProps 并且不应该是静态页面,那么它为什么要让它成为一个呢?根据 Next.js 文档,这显然不是一个,任何导出 getServerSideProps 的页面都不会是一个。那为什么会抛出错误?!?!?!
如果有帮助,这是我的 _error.tsx 文件的代码:
import React, { useEffect } from 'react';
import { GetServerSideProps } from 'next';
import Head from 'next/head';
import Router from 'next/router';
import { makeStyles, createStyles } from '@material-ui/core/styles';
import Container from '@material-ui/core/Container';
import useStandardHeaderTags from '../lib/useStandardHeaderTags';
import TitleElement from '../components/TitleElement';
const useStyles = makeStyles(() =>
createStyles({
root: {
textAlign: 'center'
}
})
);
interface Props {
statusCode: number;
}
const Error: React.FC<Props> = ({ statusCode }) => {
const classes = useStyles();
const title = statusCode === 404 ? '404' : 'Error';
return (
<>
<Head>
{useStandardHeaderTags(title)}
</Head>
<Container className={classes.root}>
<TitleElement text={title} />
{statusCode === 404
? 'The page you are looking for could not be found.'
: 'An error occurred.'}
</Container>
</>
);
};
export const getServerSideProps: GetServerSideProps = async ({ res, req }) => {
const statusCode = res ? res.statusCode : 404;
if (statusCode === 404) {
if (req.url.match(/\/$/)) {
const withoutTrailingSlash = req.url.substr(0, req.url.length - 1);
if (res) {
res.writeHead(303, {
Location: withoutTrailingSlash
});
res.end();
}
else {
Router.push(withoutTrailingSlash);
}
}
}
return {
props: {
statusCode
}
};
};
export default Error;
【问题讨论】:
标签: javascript node.js reactjs next.js