面试题答案
一键面试- 步骤:
- 在页面组件中获取动态路由参数
id
。 - 当
id
不存在时,设置一个默认值。 - 使用默认值渲染页面。
- 在页面组件中获取动态路由参数
- 代码示例(假设使用
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;