问题描述
我正在尝试在我的 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. 如何查询 category
中的 getServerSideProps
以及如何命名和嵌套页面模板?我也读了这个 ,这似乎是在正确的轨道上,但我不知道如何实现它。这是我的 [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,},};
};
解决方法
您走在正确的轨道上,您可以使用 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,},};
};