面试题答案
一键面试在Next.js的动态路由页面组件 pages/post/[id].js
中,可以通过以下方式获取动态路由参数 id
的值:
-
使用
getStaticProps
或getServerSideProps
函数:- 在
getStaticProps
或getServerSideProps
函数中,通过上下文对象context
来获取路由参数。这两个函数的第一个参数都是一个上下文对象context
,其中context.params
包含了动态路由参数。例如:
export async function getStaticProps(context) { const { id } = context.params; // 可以在这里根据id获取数据 const post = await fetchPostById(id); return { props: { post }, revalidate: 60 // 仅适用于增量静态再生 }; } export async function getServerSideProps(context) { const { id } = context.params; // 可以在这里根据id获取数据 const post = await fetchPostById(id); return { props: { post } }; }
- 这里获取到的
id
可以用于从数据库或其他数据源获取对应的数据,并通过props
传递给页面组件。
- 在
-
在客户端组件中使用
useRouter
hook:- 如果需要在客户端获取动态路由参数,可以使用
next/router
中的useRouter
hook。例如:
import { useRouter } from 'next/router'; const PostPage = () => { const router = useRouter(); const { id } = router.query; return ( <div> <p>Post ID: {id}</p> </div> ); }; export default PostPage;
router.query
是一个包含所有路由参数的对象,通过解构可以获取id
参数的值。这种方式适用于在客户端进行一些与路由参数相关的操作,比如动态更新UI等。
- 如果需要在客户端获取动态路由参数,可以使用