MST

星途 面试题库

面试题:Next.js中基于文件系统的页面路由解析 - 嵌套路由与动态嵌套

Next.js支持嵌套路由,例如`pages/products/[productId]/details.js`。如果在`details.js`页面不仅要获取`productId`,还需要支持在这个基础上的动态嵌套(如`pages/products/[productId]/details/[section].js`),请描述如何设计路由结构以及在代码层面如何处理多个动态参数,并且说明如何确保SEO友好。
44.3万 热度难度
前端开发Next.js

知识考点

AI 面试

面试题答案

一键面试

路由结构设计

  1. 文件系统路由:在 Next.js 中,继续遵循文件系统路由的约定。对于pages/products/[productId]/details/[section].js这样的结构,Next.js 会自动将其识别为嵌套路由。[productId][section]都是动态参数。
  2. 目录结构:保持清晰的目录结构有助于维护和理解路由。确保details文件夹及其子路由文件结构明确,例如:
pages/
  products/
    [productId]/
      details/
        [section].js

代码层面处理多个动态参数

  1. 获取参数:在[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;
  1. 数据获取:如果需要根据这些参数获取数据,可以在getStaticPropsgetServerSideProps中使用这些参数。例如:
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 友好

  1. 静态生成:使用getStaticPropsgetStaticPaths进行静态页面生成。这使得搜索引擎爬虫可以直接访问预先生成的 HTML 页面,提高可爬取性。
  2. Meta 标签:在页面组件中设置合适的 meta 标签,如titledescription等,以描述页面内容。可以根据动态参数来动态生成这些 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;
  1. 规范 URL:保持 URL 结构清晰、简洁且语义化。避免使用过长或复杂的 URL,确保动态参数有明确的含义,有助于搜索引擎理解页面内容。