在 Next.js 中,getStaticProps
是一个重要的数据获取方法,用于在构建时生成静态页面。以下是关于如何传递和使用 getStaticProps
参数的几种方法:
getStaticProps
函数返回的对象会自动作为 props 传递给页面组件:
export async function getStaticProps() {
const data = await fetchData(); // 获取数据
return {
props: {
posts: data // 这个 posts 会作为 props 传递给页面组件
}
};
}
function Blog({ posts }) { // 接收 props
return (
<ul>
{posts.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
);
}
当使用动态路由时,可以通过 context.params
获取路由参数:
// pages/posts/[id].js
export async function getStaticProps(context) {
const { id } = context.params; // 获取动态路由参数
const post = await getPostById(id);
return {
props: {
post
}
};
}
export async function getStaticPaths() {
const posts = await getAllPosts();
const paths = posts.map((post) => ({
params: { id: post.id.toString() },
}));
return {
paths,
fallback: false,
};
}
function Post({ post }) {
// 渲染 post 数据
}
你可以传递任意数量的参数:
export async function getStaticProps() {
const posts = await getPosts();
const categories = await getCategories();
return {
props: {
posts,
categories,
someOtherData: 'value'
}
};
}
function Page({ posts, categories, someOtherData }) {
// 使用所有 props
}
export async function getStaticProps() {
return {
props: {
// ...
},
revalidate: 10, // 每10秒重新生成页面
};
}
export async function getStaticProps() {
const apiUrl = process.env.API_URL;
const data = await fetch(`${apiUrl}/posts`);
return {
props: {
posts: await data.json()
}
};
}
export async function getStaticProps() {
try {
const data = await fetchData();
return {
props: {
data
}
};
} catch (error) {
return {
notFound: true, // 返回404页面
// 或者
// redirect: {
// destination: '/error',
// permanent: false,
// },
};
}
}