实验应用目录中双嵌套动态路由



我使用NextJS 13并在app文件夹中执行以下操作。

我试图使用generateStaticParams函数来实现静态生成页面。

这是路由:subpage/[categoryName]/[gifId]

所以路由可以像下面的例子一样。

/subpage/fashion/1
/subpage/fashion/2
/subpage/fashion/3
/subpage/technology/1
/subpage/technology/2
/subpage/technology/3
/subpage/technology/4
... and so on. 

路线subpage/[categoryName]将没有任何东西。可能显示错误或重定向某些地方。

必须包含[gifId]的完整路径subpage/[categoryName]/[gifId]

我需要执行REST请求来获取页面的数据。

我如何在我的page.tsx文件中设置这个,该文件将位于:subpage/[categoryName]/[gifId]/page.tsx?

如果它是一个单一的动态路径,将直接向前。请看下面我的实现。

但是由于嵌套了2个动态路径[categoryName][gifId]背靠背,有点困惑如何实现这一点。请协助。

import MyComponent from "../../../components/MyComponent";
import { PartialGifProps, TagType} from "../../../utils/typings";
import axios from "axios";
import {apiDomain, defaultHeaders} from "../../../utils/constants";
const perPage = 40;
type Props = {
params: {
gifId: string,
},
}
export const generateStaticParams = async () => {
const url = `${apiDomain}/get_gif_count`; // I have access to modify the backend for this if it should contain category. 
const fetchGifs = await axios.get(url, { headers: defaultHeaders });

const { total_count: totalCount } : TagType = fetchGifs.data;
const totalPages = Math.ceil(totalCount / perPage);
let paramsList = [];
for (let i = 1; i <= totalPages; i++) {
paramsList.push({ gifId: i.toString() })
}
// this paramsList would look like: 
// [
//   { gifId: '1', },
//   { gifId: '2', },
//   { gifId: '3', },
//   .......
// ]
return paramsList;
}
const MyPage = async ({params: {gifId}}: Props) => {
const url = `${apiDomain}/get_partial?page=${gifId}&per_page=${perPage}`;
const fetchGifs = await axios.get(url, { headers: defaultHeaders });
const { gifs } : PartialGifProps = fetchGifs.data;
return (
<div className='text-white'>
<MyComponent gifs={gifs}/>
</div>
);
};
export default MyPage;

您可以通过paramsprop以获得gifId的相同方式获得categoryName

type Props = {
params: {
gifId: string,
categoryName: string,
},
}
const MyPage = async ({params: {gifId, categoryName}}: Props) => {
console.log('categoryName =', categoryName);
const url = `${apiDomain}/get_partial?page=${gifId}&per_page=${perPage}`;
const fetchGifs = await axios.get(url, { headers: defaultHeaders });
const { gifs } : PartialGifProps = fetchGifs.data;
return (
<div className='text-white'>
<MyComponent gifs={gifs}/>
</div>
);
};

最新更新