【问题标题】:How to clear/delete cache in NextJs?如何清除/删除 NextJs 中的缓存?
【发布时间】:2021-09-27 08:29:43
【问题描述】:

我在/products/[slug].js有一个产品页面

我为 wordpress/graphql 网站使用增量静态生成:

export async function getStaticProps(context) {

    const {params: { slug }} = context

    const {data} = await client.query(({
        query: PRODUCT_SLUG,
        variables: { slug }
    }));

    return {
        props: {
            categoryName: data?.productCategory?.name ?? '',
            products: data?.productCategory?.products?.nodes ?? []
        },
        revalidate: 1
    }

}

export async function getStaticPaths () {
    const { data } = await client.query({
        query: PRODUCT_SLUGS,
    })

    const pathsData = []

    data?.productCategories?.nodes && data?.productCategories?.nodes.map((productCategory) => {
        if (!isEmpty(productCategory?.slug)) {
            pathsData.push({ params: { slug: productCategory?.slug } })
        }
    })

    return {
        paths: pathsData,
        fallback: true,
    }
}

除了一件事之外,一切都按预期进行。如果我从 wordpress 中删除以前发布的产品,NextJs 会提供缓存页面而不是显示404 - Not found 页面,我认为这就是它应该工作的方式,这意味着如果没有重建某些东西,则显示上一个(过时的)页面。

但是,如何才能完全删除已删除的特定产品的缓存,并且不会再次从 PRODUCT_SLUGS 查询中获取?

我已经阅读了fallback 选项:true, false, blocking,但它们似乎都不起作用。

是否有解决方案,next.config.js 配置或其他解决方法?

【问题讨论】:

标签: wordpress caching next.js apollo nextjs-dynamic-routing


【解决方案1】:

所以我遇到了同样的问题,虽然我使用的是 GraphCMS。所以这是你需要做的修复:

    export async function getStaticProps(context) {
    const {params: { slug }} = context

    const {data} = await client.query(({
        query: PRODUCT_SLUG,
        variables: { slug }
    }));

    if (!data) {
        return {
            notFound: true
        }
    } else {
        return {
            props: {
                categoryName: data?.productCategory?.name ?? '',
                products: data?.productCategory?.products?.nodes ?? []
            },
            revalidate: 1
        }
    }
}

您需要在getStaticProps中返回notFound: true

notFound - 一个可选的布尔值,允许页面返回 404 状态和页面。

请参阅文档中的此页面 https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation

然后在getStaticPaths 中将回退更改为fallback: "blocking"。如果您保留fallback: true,它将提供旧页面,因为该页面已成功构建。

【讨论】:

    猜你喜欢
    • 2012-11-12
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 2012-02-24
    • 2012-01-31
    • 2017-02-20
    • 2019-09-18
    • 2022-01-22
    相关资源
    最近更新 更多