首页 > 解决方案 > Nextjs 动态路由 - 如何将道具从父级传递给动态路由子级

问题描述

使用 next@latest 及其动态路由功能。我有

/pages/index.tsx/pages/department/[slug]/index.tsx。第一个 index.tsxgetStaticProps用于拉入一些数据。在开发期间,此数据是自动生成的对象数组。然后我通过索引组件中的 props.departments 渲染这些对象。

我正在显示部门列表,并希望将项目链接到单个页面:

{departments.map(dept => (
  <Link
    as={`/department/${dept.slug}`}
    href="/department/[slug]"
  >
    ...
  </Link>
)}

似乎没有办法传递道具,因为没有明显的父/子连接。

我是否必须在 [slug]/index.tsx 中查询单个部门,我应该使用 react useContext,还是有更好的设计方法可以解决这个问题?

感谢您的任何指导。

标签: reactjsnext.js

解决方案


如果您选择使用上下文 API 在两个路由之间共享状态,/pages/index.tsx并且/pages/department/[slug]/index.tsx您必须将App组件与上下文提供程序一起包装在_app.tsx. 这将导致另一个问题,如果您还有另外三个不需要数据的路由,它们也将成为上下文提供者的子级,而不使用上下文中的值。

我建议在数据获取方法中查询数据,即getStaticPathsgetStaticProps如果使用静态生成并且getServerSideProps为单个部门使用服务器端渲染。

这是一些伪代码的样子/pages/department[slug]/index.tsx

如果使用静态生成

export const getStaticPaths: GetStaticPaths = async () => {
  let paths: {params: { slug: string;}}[] = [];

  // generate the paths for the pages you want to render
  return {
    paths,
    fallback: false // false if you know all the slugs that you want to generate ahead of time  
  }

}

interface IProps {
  // props for your page
}

export const getStaticProps: GetStaticProps<IProps> = async (context) => {
   // get the slug
   const slug = context.params?.slug;

   // query the data based on slug

   return {
     props: {
       // return the queried data as props
     }
   }
}

如果使用服务器端渲染

interface IProps {
  // data you need as props
}

export const getServerSideProps: GetServerSideProps<IProps> = async (context) => {
  // get the slug
  const slug = context.params.slug

  // query the data

  return {
    props: {
       // return the queried data
    } 

  }

}

PS-getStaticProps将为getStaticPaths构建时返回的每个路径调用一次。getServerSideProps将根据请求调用,因此请根据需要选择要如何获取数据。


推荐阅读