路由结构设计
- 文件系统路由:在 Next.js 中,继续遵循文件系统路由的约定。对于
pages/products/[productId]/details/[section].js
这样的结构,Next.js 会自动将其识别为嵌套路由。[productId]
和[section]
都是动态参数。
- 目录结构:保持清晰的目录结构有助于维护和理解路由。确保
details
文件夹及其子路由文件结构明确,例如:
pages/
products/
[productId]/
details/
[section].js
代码层面处理多个动态参数
- 获取参数:在
[section].js
页面组件中,可以通过useRouter
钩子来获取动态参数。
import { useRouter } from 'next/router';
const SectionPage = () => {
const router = useRouter();
const { productId, section } = router.query;
return (
<div>
<p>Product ID: {productId}</p>
<p>Section: {section}</p>
</div>
);
};
export default SectionPage;
- 数据获取:如果需要根据这些参数获取数据,可以在
getStaticProps
或getServerSideProps
中使用这些参数。例如:
import { useRouter } from 'next/router';
const SectionPage = ({ productData, sectionData }) => {
return (
<div>
<p>Product Data: {JSON.stringify(productData)}</p>
<p>Section Data: {JSON.stringify(sectionData)}</p>
</div>
);
};
export async function getStaticProps(context) {
const { productId, section } = context.params;
const productData = await fetchProductData(productId);
const sectionData = await fetchSectionData(productId, section);
return {
props: {
productData,
sectionData
},
revalidate: 60 // 可选的增量静态再生
};
}
export async function getStaticPaths() {
const productIds = await getAllProductIds();
const paths = productIds.flatMap(productId => {
const sections = getSectionsForProduct(productId);
return sections.map(section => ({
params: { productId, section }
}));
});
return { paths, fallback: false };
}
export default SectionPage;
确保 SEO 友好
- 静态生成:使用
getStaticProps
和getStaticPaths
进行静态页面生成。这使得搜索引擎爬虫可以直接访问预先生成的 HTML 页面,提高可爬取性。
- Meta 标签:在页面组件中设置合适的 meta 标签,如
title
、description
等,以描述页面内容。可以根据动态参数来动态生成这些 meta 标签内容。
import { useRouter } from 'next/router';
import Head from 'next/head';
const SectionPage = ({ productData, sectionData }) => {
const router = useRouter();
const { productId, section } = router.query;
return (
<div>
<Head>
<title>{`${section} - ${productData.title}`}</title>
<meta name="description" content={`Details about ${section} of product ${productData.title}`} />
</Head>
<p>Product Data: {JSON.stringify(productData)}</p>
<p>Section Data: {JSON.stringify(sectionData)}</p>
</div>
);
};
//...其他代码
export default SectionPage;
- 规范 URL:保持 URL 结构清晰、简洁且语义化。避免使用过长或复杂的 URL,确保动态参数有明确的含义,有助于搜索引擎理解页面内容。