【问题标题】:getStaticPaths not creating paths on productiongetStaticPaths 未在生产中创建路径
【发布时间】:2021-08-24 19:47:46
【问题描述】:

我正在尝试连接 WordPress 和 next.js,并且在 dev 上一切正常,但生产版本有一个问题。

我有一个显示所有帖子的页面,在 WP 中添加新帖子后,我可以看到这个新添加的帖子,但是当我尝试打开链接时,我得到 404。我确定这个问题是由 getStaticPaths 引起。

这就是我的 slug 页面的样子

import {getAllPost, getPostBySlug} from "../../lib/api";

const PostPage = ({post}) => {
    return (
        <div className="container">
            <h1>{post.title}</h1>
            <div dangerouslySetInnerHTML={{__html: post.content}}/>
        </div>
    )
}

export const getStaticProps = async (ctx) => {

    const {slug} = ctx.params
    const post = await getPostBySlug(slug)

    return {
        props: {
            post
        },
        revalidate: 10
    }
}

export const getStaticPaths = async () => {
    const posts = await getAllPost()

    const paths = posts.map(post => ({
        params: {slug: post.slug}
    }))

    return {
        paths,
        fallback: false
    }
}

export default PostPage

getStaticPaths() 中的 getAllPost() 函数返回包含帖子标题和 slug 的对象数组。

【问题讨论】:

    标签: next.js


    【解决方案1】:

    您在静态路径中使用fallback: false,这意味着只有在构建期间可用的路径(在您的情况下为帖子)可以静态生成。所以不会显示其他帖子页面。

    为了能够在部署项目后显示新添加的帖子,请使用fallback: true。

    【讨论】:

    • 谢谢,取得了一些进展,但现在我有错误```无法读取未定义的属性'标题'```
    • 在此错误期间,您的 slug 参数在 getStaticProps 中的外观如何?那么 getSlugByPost 的结果是什么?
    猜你喜欢
    • 2021-04-06
    • 2022-06-23
    • 1970-01-01
    • 1970-01-01
    • 2020-10-18
    • 2020-08-18
    • 1970-01-01
    • 2018-01-07
    • 1970-01-01
    相关资源
    最近更新 更多