方法如getServerSideProps https://nextjs.org/docs/pages/building-your-application/data-fetching/get-server-side-props and getStaticProps https://nextjs.org/docs/pages/building-your-application/data-fetching/get-static-props用于在服务器上获取数据,但它们仅适用于内部的页面组件pages https://nextjs.org/docs/getting-started/project-structure文件夹(在 Next.js 中设置路由的初始方法)。
从 Next.js 13 开始,在app https://nextjs.org/docs/getting-started/project-structure目录(当您对下图中显示的最后一个问题回答“是”时使用)我们有服务器组件 https://nextjs.org/docs/getting-started/react-essentials#server-components,您可以直接在组件主体中获取数据,如下面的代码片段所示(请阅读注释):
/*
If you want to access headers or cookies while fetching data,
you can use these functions:
*/
import { cookies, headers } from "next/headers";
/*
If the below component is the default export of a `page.js` and you are using
dynamic routes, slugs will be passed as part of `params`, and
query strings are passed as part of `searchParams`.
*/
export default async function Component({ params, searchParams }) {
/*
This request should be cached until manually invalidated.
Similar to `getStaticProps`.
`force-cache` is the default and can be omitted.
*/
const staticData = await fetch(`https://...`, { cache: "force-cache" });
/*
This request should be refetched on every request.
Similar to `getServerSideProps`.
*/
const dynamicData = await fetch(`https://...`, { cache: "no-store" });
/*
This request should be cached with a lifetime of 10 seconds.
Similar to `getStaticProps` with the `revalidate` option.
*/
const revalidatedData = await fetch(`https://...`, {
next: { revalidate: 10 },
});
return "...";
}
也就是说,您无需fetch()
,使用任何库,甚至直接使用 ORM 与数据库对话,在这种情况下您可以使用路由段配置 https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config:
// layout.js OR page.js OR route.js ????????
import prisma from "./lib/prisma";
/*
Keep one of the possibilities shown below (there are more on the doc),
depending on your needs.
*/
export const revalidate = 10; // If you want to revalidate every 10s
// OR
export const dynamic = "force-dynamic"; // If you want no caching at all
// ...
async function getPosts() {
const posts = await prisma.post.findMany();
return posts;
}
export default async function Page() {
const posts = await getPosts();
// ...
}