【发布时间】:2021-05-04 01:02:06
【问题描述】:
我的 Next.js 项目中有一个 [pid].js 文件。我还想实现一个自定义 404 页面,但问题是:我将 404.js 文件放在 /pages 目录中。如果我删除我的[pid].js 文件,404 页面就可以正常工作。但是,如果我保留我的 [pid].js 文件,第一个请求会进入 pids,并且由于 url 与 pids 中定义的任何页面都不匹配,我会收到错误消息。我应该从 pid 显式返回我的 404 组件吗?这是一个好习惯吗?
这里是代码(现在不会重定向到 404 页面):
[pid].js
const Pid = ({ url, props }) => {
const getPages = () => {
let component = null;
switch (url) {
case 'checkout':
component = <CheckoutPage {...props} />;
break;
//other switch cases...
default:
//should I return my 404 component here?
component = <DefaultPage {...props} />;
}
return component;
};
return getPages();
};
export async function getServerSideProps(context) {
const res = await getReq(`/getUrl`, 'content', context);
switch (res.url) {
case 'checkout': {
return {
props: {
url: res.url,
props: {
... //my other props
},
},
};
}
default:
return {
props: null,
};
}
}
Pid.propTypes = {
url: PropTypes.string.isRequired,
};
export default Pid;
【问题讨论】:
标签: javascript next.js