如何避免“加载”不存在的静态页面 Next.JS

问题描述

我正在制作电子商务 Next.JS 静态应用。

对于我的产品页面,我使用带有 fallback: true 和简单 useRouter 的增量静态生成(我会进一步称其为 ISG)来显示加载组件(如微调器或其他东西,它没有)没关系)。 ISG 对于频繁更新数据的静态站点(如添加评论、新产品等)非常有用,但如果我没有产品路径(例如 /products/nike-pants-12345),页面将返回“无限加载”和错误

错误如下。

Error with non-exist page for ISG

如果我们查看控制台,我们可以看到类似:TypeError: Cannot read property '_id' of null。这意味着应用没有找到具有请求 _id 的产品(可能是名称、slug 等)。

那么,问题是我如何才能避免这种情况,是否应该完全避免这种情况?

提前致谢!

>>

export async function getStaticPaths() {
    await dbConnect()

    const products = await ProductModel.find({})

    const paths = products.map((doc) => {
        const product = doc.toObject()
        return {
            params: { id: product._id.toString() }
        }
    })

    /* fallback: true means that the missing pages
    will not 404,and instead can render a fallback */
    return { paths,fallback: true }
}

export async function getStaticProps({ params }) {
    await dbConnect()

    const product = await ProductModel.findById(params.id).lean()
    product._id = product._id.toString()

    // revalidate set the time (in sec) of re-generate page (it imitate SSR)
    return { props: { product },revalidate: 30 }
}

解决方法

使回退“阻塞”而不是真实

,

您可以通过添加对 product 的检查来触发 404 页面,如果在 notFound: true 中没有找到产品,则返回 getStaticProps

export async function getStaticProps({ params }) {
    await dbConnect()

    const product = await ProductModel.findById(params.id).lean()

    if (!product) {
        return {
            notFound: true
        }
    }

    product._id = product._id.toString()

    // revalidate set the time (in sec) of re-generate page (it imitate SSR)
    return { props: { product },revalidate: 30 }
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...