[英]How to get page slug in the app directory in Next 13?
In Next.js 12, we got the slug of the current page by doing as below in a getStaticProps
.在 Next.js 12 中,我们通过在
getStaticProps
中执行以下操作来获取当前页面的 slug。 How can this be done in Next.js 13? Next.js 13 中如何做到这一点?
✅Next.js 12 ✅Next.js 12
export async function getStaticProps(context) {
const slug = context.params.slug
}
❌Next.js 13 - In Next.js13, using the above code gives this error ❌Next.js 13 - 在 Next.js13 中,使用上面的代码会报错
Error: Cannot read properties of undefined (reading 'params')
export async function fetchData(context) {
❌const slug = context.params.slug
}
In the app
directory, your component, located in a page.js
, gets passed a parameter that would look like this:在
app
目录中,位于page.js
中的组件会传递一个如下所示的参数:
{ params: {}, searchParams: {} }
If you have a slug
, it would be in params
.如果你有
slug
,它会在params
中。 But it's your page component that should pass it to your data fetching function, as an example like so:但它是您的页面组件,应该将它传递给您的数据获取 function,例如:
async function fetchData(context) {
const slug = context.params.slug
}
export default async function Page(context) {
const data = await fetchData(context)
return <h1>My Page</h1>;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.