MST

星途 面试题库

面试题:Next.js中如何为动态路由参数设置默认值

在Next.js项目里,有一个页面使用了动态路由,比如`pages/post/[id].js`,现在要求为`id`这个动态路由参数设置一个默认值,以便在没有传递`id`参数时也能正常显示页面并给出默认内容。请描述实现此功能的具体步骤和代码示例。
25.2万 热度难度
前端开发Next.js

知识考点

AI 面试

面试题答案

一键面试
  1. 步骤
    • 在页面组件中获取动态路由参数id
    • id不存在时,设置一个默认值。
    • 使用默认值渲染页面。
  2. 代码示例(假设使用getStaticProps获取数据)
import React from'react';

const PostPage = ({ postId }) => {
  const displayId = postId || 'default - id';
  return (
    <div>
      <p>The post ID is: {displayId}</p>
    </div>
  );
};

export async function getStaticProps({ params }) {
  const postId = params.id;
  return {
    props: {
      postId
    },
    revalidate: 60
  };
}

export async function getStaticPaths() {
  // 这里假设你有一些动态路径的逻辑
  const paths = [
    { params: { id: '1' } },
    { params: { id: '2' } }
  ];
  return { paths, fallback: false };
}

export default PostPage;

在上述代码中,getStaticProps获取id参数,在PostPage组件中,当postId不存在时,使用'default - id'作为默认值进行页面渲染。如果使用getServerSideProps,代码结构类似,只是数据获取逻辑在服务器端执行:

import React from'react';

const PostPage = ({ postId }) => {
  const displayId = postId || 'default - id';
  return (
    <div>
      <p>The post ID is: {displayId}</p>
    </div>
  );
};

export async function getServerSideProps({ params }) {
  const postId = params.id;
  return {
    props: {
      postId
    }
  };
}

export default PostPage;