代码之家  ›  专栏  ›  技术社区  ›  Jesse Winton

如何命名Next js中嵌套动态路由的页面模板

  •  0
  • Jesse Winton  · 技术社区  · 4 年前

    我正在努力实现一个动态路由结构,在我的下一个JS应用程序中使用Prismic。基本上,我有一页, mysite.com/landing-page 例如,我可以在我的 [uid] 模板,使用 { uid } = params 在我的 getServerSideProps 作用但是,我希望允许用户通过子目录访问同一页面,例如 mysite.com/sacramento-ca/landing-page .我所做的研究似乎表明,我可以在我的Prismic存储库中创建一个内容关系,指定页面也可以引用的位置( sacramento-ca 作为示例),然后引用我的查询中的内容,并将其传递给页面模板。然而,我不知道如何实现这一点。

    我的 pages 目录的结构如下所示:

    ├── [uid]
    │   └── index.tsx
    ├── index.tsx
    ├── products
    │   └── [uid].tsx
    ├── projects
    │   └── index.tsx
    ├── promos
    │   ├── [id].tsx
    │   └── index.tsx
    └── sitemap
        └── index.tsx
    

    …总的来说,这对顶级页面来说很好。但是1。我如何查询 category 在里面 getServerSideProps 我该如何命名和嵌套页面模板?我读了这个 question/answer 同样,这似乎是在正确的轨道上,但我不知道如何实现它。这是我的密码 [uid] 还有模板,以防有用。

    import React from 'react';
    
    import { SEO } from 'components/seo/SEO';
    import { SliceZone } from 'components/slice-zone/SliceZone';
    
    import { client, queryWithProducts } from '../../lib/prismic';
    
    export const Page = ({ document }: any) => {
      const slices = document;
      if (!slices) return null;
    
      const { meta_title, meta_description, meta_keywords, social_image } = document;
    
      return (
        <>
          <SEO
            title={meta_title}
            description={meta_description}
            keywords={meta_keywords}
            banner={social_image.url}
          />
          <SliceZone slices={slices} />
        </>
      );
    };
    
    export default Page;
    
    export const getServerSideProps = async ({ params, query }: any) => {
      console.log(query)
      const { uid } = params;
      const { data: document } = await client.getByUID('landing', uid, queryWithProducts);
    
      return {
        props: {
          document,
        },
      };
    };
    
    0 回复  |  直到 4 年前
        1
  •  1
  •   juliomalves    4 年前

    你在正确的轨道上,你可以使用 dynamic catch-all route .

    您需要将文件夹重命名为 [...uid] ,这将使 params.uid 返回和数组,而不是字符串。

    // [...uid]/index.tsx
    
    export const getServerSideProps = async ({ params, query }: any) => {
        const { uid } = params; 
        // When navigating to /sacramento-ca/landing-page `uid` will 
        // be an array containing ['sacramento-ca', 'landing-page']
    
        // Add logic to retrieve data based on array values
    
        return {
            props: {
                document,
            },
        };
    };