【问题标题】:How do I name page templates for nested dynamic routing in Next js?Next js中如何为嵌套动态路由命名页面模板?
【发布时间】:2021-04-19 00:47:21
【问题描述】:

我正在尝试在我的 Next.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. 如何查询 getServerSideProps 中的 category 以及如何命名和嵌套页面模板?我也读过这个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,
    },
  };
};

【问题讨论】:

    标签: reactjs next.js server-side-rendering dynamic-routing


    【解决方案1】:

    你在正确的轨道上,你可以使用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,
            },
        };
    };
    

    【讨论】:

    • 好的,我已经掌握了这项工作的基础知识。我唯一苦苦挣扎的是,我无法弄清楚如何解析数组值以从Prismic 获取数据。本质上,sacramento-ca/interior-doors 有效,但是当我只访问interior-doors 时,我收到一个错误,说我的Prismic 客户端需要一个字符串文字。
    • 由于位置 sacramento-ca 是可选的,因此您应该调整代码以支持它 - 您可以检查 uid 数组长度并根据它以不同方式从 Prismic 查询数据。跨度>
    • 我现在写的内容类似于:const parsed = _.isArray(uid) ? uid[1] : uid[0],然后我将parsed 传递给我的 Prismic 客户端。是这个意思吗?
    • 其实uid 永远是一个数组。您需要根据它包含的项目数检查是传递第二个元素还是第一个元素。
    猜你喜欢
    • 2019-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-09
    • 2015-03-19
    • 2020-04-06
    • 1970-01-01
    • 2021-04-09
    相关资源
    最近更新 更多