You*_*mar 11 javascript reactjs next.js
例如,我们曾经使用getServerSideProps
重定向到页面组件中的 404 页面,如下所示:
// pages/index.js
export async function getServerSideProps(context) {
const placeId = context.params.placeId;
const places = await getPlace(placeId);
if (!places.length) {
return {
notFound: true,
}
}
return {
props: {
places[0],
},
};
Run Code Online (Sandbox Code Playgroud)
有了 Next.js13
和app
目录,我们就有了服务器组件。getServerSideProps
由于不再使用,如何重定向到 404 页面?
You*_*mar 17
根据文档,您可以使用notFound()
函数作为示例,如下所示,它将渲染相应的not-found.js
文件:
// app/user/page.js
import { notFound } from 'next/navigation';
export default async function Profile({ params }) {
const res = await fetch(`/user/${params.id}`);
if (!res.ok) {
notFound();
}
return <div>Actual Data</div>;
}
Run Code Online (Sandbox Code Playgroud)
// app/user/not-found.js
export default function NotFound() {
return <p>404 Not Found</p>
}
Run Code Online (Sandbox Code Playgroud)
如果没有app/user/not-found.js
文件,则使用app/not-found.js
. 如果没有app/not-found.js
,它将使用 Next.js 给出的默认值。
归档时间: |
|
查看次数: |
9242 次 |
最近记录: |