简体   繁体   English

Next 13如何获取app目录下的page slug?

[英]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.

相关问题 如何使用 Next 13 获取应用程序目录中的当前路径名? - How to get current pathname in app directory with Next 13? Next JS 13 'next build' 将应用程序目录 app/page.js 和路由组页面输出为 0 字节并导致生产中出现 404 错误 - Next JS 13 'next build' outputs app directory app/page.js and route group pages as 0 bytes and causes 404 error in production 记住为下一页 - Remember slug for next page 如何在带有应用程序目录的 NextJS 13 中使用 SVG? - How to use SVG in NextJS 13 with app directory? 如何让我的布局组件在 Next13 应用程序文件夹中保留 static - How do I get my layout component to remain static in Next13 app folder 如何从应用程序中获取 app.json `slug` 值? - How do I get the app.json `slug` value from the app? 如何在 getStaticProps 中获取 slug 值以使用参数作为 slug 调用 api - How to get slug value in getStaticProps to call api with parameter as slug 如何将 Next.js 13 中的 page.js 的道具传递给 layout.js? - How to pass props to layout.js from page.js in Next.js 13? 如何从Next.js 13的新app文件夹中的公用文件夹中导入CSS个文件? - How to import CSS files from public folder in the new app folder of Next.js 13? 用PhatomJs登录后如何获得下一页? - How get the next page after login with PhatomJs?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM