如果页面不存在,我想重定向到404页面。我按照here的说明进行操作,我的代码如下
app/[slug]/page.tsx
import { notFound } from 'next/navigation';
import { getPage } from "@/sanity/utils";
import { CustomPortableText } from "../components/CustomPortableText";
type Props = {
params: { slug: string }
}
export default async function Page({ params }: Props) {
const page = await getPage(params.slug);
if (!page) {
return notFound()
}
return (
<article>
<CustomPortableText paragraphClasses="my-6" value={page.body} />
</article>
)
}
该代码适用于现有页面。但是,当页面不存在时,groq 返回
null
并到达 notFound
语句行并显示带有控制台错误的空白页面
你能告诉我我做错了什么吗?预先感谢。
我不使用自定义 404 页面。并已阅读 NextJS 文档 上的说明,但没有运气。
如果您使用
react-redux
库或 ReactContext
,请尝试从布局组件中删除带有 Providers
的包装器...我遇到了类似的问题,这有帮助!
我还建议创建自定义未找到页面(根据文档):
./app/not-found.tsx
export default async function NotFound() {
return (
<h1>404! Not Found</h1>
);
}
通话后您不需要
return
notFound()