【问题标题】:Next.js: getStaticProps and getStaticPaths with dynamic routes to generate static filesNext.js:getStaticProps 和 getStaticPaths 用动态路由生成静态文件
【发布时间】:2020-07-17 03:33:41
【问题描述】:

我发现docs 有点模棱两可。给定一个特许经营列表,我想在构建时呈现相关的特许经营详情页面,以避免在运行时碰到 CMS/API,因为这些不会经常更改。

然而,似乎即使相关页面是在构建时使用getStaticPaths 生成的,它们仍然需要在运行时执行getStaticProps 中的调用。这违背了生成静态页面的目的。

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 的数据,并且运行时不需要任何进一步的调用来填充道具。

【问题讨论】:

    标签: next.js


    【解决方案1】:

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

    但在开发模式 next dev 中,getStaticPropsgetStaticPaths 会针对每个请求运行。

    getStaticProps (Static Generation)

    【讨论】:

    • 感谢@Nikolai 我确实在使用next dev 并在执行next buildnext start 时确认所有工作正常
    • 在开发模式下是否可以有相同的行为?只运行一次 getStaticProps?
    • getStaticProps 也将为生产中的每个请求运行,如果回退为真并且动态页面未预呈现。
    猜你喜欢
    • 2021-01-29
    • 1970-01-01
    • 2021-09-19
    • 2020-10-18
    • 2016-11-19
    • 1970-01-01
    • 2021-04-09
    • 2020-03-17
    • 2011-06-23
    相关资源
    最近更新 更多