路由设计
整个项目的路由设计可以说是这个项目的关键所在了,因为它控制着网站如何跳转
所以路由设计就显得非常重要,考虑到我们有多个项目,还有十几个组件、专栏等,所以设计了如下路由
具体实现
由于整个网站是使用 next.js 框架开发,而且 next.js 还支持动态路由,于是我们的路由结构实现如下
Nextjs 动态路由
讲 Nextjs 的动态路由,不得不提的就是 getStaticPaths 和 getStaticProps
getStaticPaths 详解
有两个动态路由 [starter] 和 [docs],所以 params 中必须要包含 starter 和 docs
export const getStaticPaths: GetStaticPaths<{
starter: string;
docs: string;
}> = async () => {
const starters = await getAllStarter();
const paths: any[] = [];
starters.forEach((starter: Article) => {
const docs = getAllDocsBySlug(starter.slug);
docs.forEach((doc: any) => {
paths.push({
params: {
starter: starter.slug,
docs: doc.slug,
},
});
});
});
return { paths, fallback: true };
};
注意 params 中必须要包含 starter 和 docs 这两个属性
因为该文件位于 \src\pages\starter[starter]\docs[docs].tsx
getStaticProps 详解
注意该方法中的 starter 和 docs 就是从 getStaticPaths 获取到的
export const getStaticProps: GetStaticProps<{
frontMatter: StarterDocs;
mdxSource: any;
toc: any;
menu: RouteItem;
}> = async ({ params }) => {
const { starter, docs }: any = params;
const menu: RouteItem = readJsonFileBySlug(SECTION, starter);
const docsFile = readMarkdownFileBySlug<StarterDocs>(
SECTION,
starter,
docs + '.md'
);
const post: any = await compileMDX(docsFile.content);
const { mdxSource, toc } = post;
return { props: { frontMatter: docsFile.data, mdxSource, toc, menu } };
};
该方法最终返回读取到的数据。
总结:getStaticPaths 和 getStaticProps 一般配对使用,getStaticPaths 负责获取 slug
getStaticProps 负责根据 getStaticPaths 获取到的动态路由读取文件数据给组件使用
getServerSideProps
getServerSideProps 这个目前官网中还没有用到,等用到之后再来做补充