Next.js:使用动态路由生成静态文件的 getStaticProps 和 getStaticPaths [英] Next.js: getStaticProps and getStaticPaths with dynamic routes to generate static files
问题描述
我发现 文档 有点含糊不清.给定一个特许经营列表,我想在构建时呈现相关的特许经营详细信息页面,以避免在运行时访问 CMS/API,因为这些页面不会经常更改.
I am finding the docs a little ambiguous. Given a list franchises, I would like to render out the relevant franchise detail pages at build time to avoid hitting the CMS/API at run time, as these don't change frequently.
然而,似乎即使在构建时使用 getStaticPaths
生成相关页面,它们仍然需要在运行时执行 getStaticProps
中的调用.这违背了生成静态页面的目的.
However, it seems that even if the relevant pages are generated at build time using getStaticPaths
, they still require the calls in getStaticProps
to be executed at runtime. This defeats the purpose of generating static pages.
import {withLayout} from '../../components/layout';
import {getFranchises} from '../api/franchises';
const Franchise = (props) => {
console.info(props);
return (
<>
<h1>{props.name}</h1>
</>
);
};
export async function getStaticProps({params}) {
let data = await getFranchises();
let franchise = data.find(x => x.id === params.id);
return {
props: franchise
}
}
export async function getStaticPaths() {
let data = await getFranchises();
// Get the paths we want to pre-render based on posts
const paths = data.map(post => ({
params: {id: post.id},
}));
// We'll pre-render only these paths at build time.
return {paths, fallback: false}
}
export default withLayout(Franchise);
也许,我做错了什么,但我真的在寻找一些关于如何在构建时使用 next build
生成静态页面的文档/演示,它使用来自 build 的 API 的数据 时间并且不需要任何进一步的调用来在运行时填充道具.
Perhaps, I am doing something wrong, but I really am looking for some docs/demo on how to generate static pages at build time using next build
that uses data from API at build time and does not require any further calls to populate props at runtime.
推荐答案
getStaticProps
和 getStaticPaths
都只在构建时运行.这就是这些功能的目的.您使用正确.
Both getStaticProps
and getStaticPaths
run only at build time. That is the purpose of these functions. You are using it correctly.
在开发模式 next dev
中,getStaticProps
和 getStaticPaths
在每个请求上运行.
In development mode next dev
, however, getStaticProps
and getStaticPaths
run on every request.
这篇关于Next.js:使用动态路由生成静态文件的 getStaticProps 和 getStaticPaths的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!