MST

星途 面试题库

面试题:Next.js中如何设置404页面以及自定义简单的路由规则

在Next.js项目中,描述设置404页面的具体步骤,并举例说明如何自定义一个简单的路由规则,比如将 /products/:id 路由到特定的页面组件。
31.8万 热度难度
前端开发Next.js

知识考点

AI 面试

面试题答案

一键面试

设置404页面步骤

  1. pages 目录下创建 404.js 文件。
  2. 404.js 中编写404页面的UI和逻辑。例如:
import React from 'react';

const Custom404 = () => {
  return (
    <div>
      <h1>404 - Page Not Found</h1>
      <p>The page you are looking for does not exist.</p>
    </div>
  );
};

export default Custom404;

自定义路由规则示例

  1. pages 目录下创建 products 目录。
  2. products 目录下创建 [id].js 文件。这个 [id] 就是动态路由参数。
  3. [id].js 中编写页面组件逻辑,例如:
import React from 'react';

const ProductPage = ({ query }) => {
  const { id } = query;
  return (
    <div>
      <h1>Product Page - {id}</h1>
      <p>This is the page for product with ID: {id}</p>
    </div>
  );
};

export default ProductPage;

这样,当访问 /products/123 时,就会渲染 ProductPage 组件,并把 id 参数传递进去。