[英]Dynamic route prevents redirecting to 404 page in Next.js
我的 Next.js 项目中有一个[pid].js
文件。 我也想实现自定义 404 页面,但问题是:我将404.js
文件放在/pages
目录中。 如果我删除我的[pid].js
文件,404 页面就可以正常工作。 但是,如果我保留我的[pid].js
文件,第一个请求进入 pids,并且由于 url 与 pids 中定义的任何页面都不匹配,我得到一个错误。 我应该明确地从 pids 返回我的 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;
从 NextJS 10 开始,由于新标志notFound: true
,您不必显式返回 404 页面。 您可以在getStaticProps
和getServerSideProps
中使用它来自动触发默认 404 页面或您自己的自定义 404 页面。
从 NextJS 文档中查看这些示例。
export async function getStaticProps(context) {
const res = await fetch(`https://.../data`)
const data = await res.json()
if (!data) {
return {
notFound: true,
}
}
return {
props: { data }, // will be passed to the page component as props
}
}
export async function getServerSideProps(context) {
const res = await fetch(`https://...`)
const data = await res.json()
if (!data) {
return {
notFound: true,
}
}
return {
props: {}, // will be passed to the page component as props
}
}
从 Next.js 10 开始,您可以从getServerSideProps
返回notFound: true
以触发 404 页面。
export async function getServerSideProps(context) {
const res = await getReq(`/getUrl`, 'content', context);
switch (res.url) {
case 'checkout': {
return {
props: {
//my other props
},
};
}
default:
return {
notFound: true
};
}
}
作为示例,我已将它放在default
情况下,但您可以在任何其他点/条件下随意返回它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.