Next.js:getStaticProps 和 getStaticPaths 用动态路由生成静态文件 [英] Next.js: getStaticProps and getStaticPaths with dynamic routes to generate static files

查看:38
本文介绍了Next.js:getStaticProps 和 getStaticPaths 用动态路由生成静态文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现 docs 有点模棱两可.给定一个特许经营列表,我想在构建时呈现相关的特许经营详情页面,以避免在运行时碰到 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 生成静态页面的文档/演示,它使用来自 API 的数据 build 时间,并且不需要任何进一步的调用来在 运行时 填充道具.

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.

推荐答案

getStaticPropsgetStaticPaths 都只在 构建时 运行.这就是这些功能的目的.你用对了.

Both getStaticProps and getStaticPaths run only at build time. That is the purpose of these functions. You are using it correctly.

然而,在开发模式 next dev 中,getStaticPropsgetStaticPaths 在每个请求上运行.

In development mode next dev, however, getStaticProps and getStaticPaths run on every request.

getStaticProps(静态生成)

这篇关于Next.js:getStaticProps 和 getStaticPaths 用动态路由生成静态文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆