Next.js ISR页面在CMS中删除后没有被删除 [英] Next.js ISR page not being deleted after deleting it in CMS

查看:80
本文介绍了Next.js ISR页面在CMS中删除后没有被删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试 Next.js 并构建一个小应用程序,该应用程序从安装了 GraphQL 的无头 WordPress 应用程序中获取帖子.然后我使用 Apollo/Client 获取 GraphQL 内容:

apollo-client.js

import { ApolloClient, InMemoryCache } from "@apollo/client";const 客户端 = 新 ApolloClient({uri:process.env.WORDPRESS_GRAPHQL_ENDPOINT,缓存:新的 InMemoryCache(),});导出默认客户端;

在索引中我抓取帖子:

index.js

从next/head"导入头部;从../styles/Home.module.css"导入样式;import { gql } from "@apollo/client";从下一个/链接"导入链接;从../apollo-client"导入客户端;功能首页(道具){const { 帖子} = 道具;返回 (<div className={styles.container}><头><title>Wordpress 博客文章</title><元名称=说明"content=带有 Apollo 客户端的 Wordpress 博客文章";/><link rel="icon";href="/favicon.ico";/></头><main className={styles.main}>=<div className={styles.grid}>{posts.map((post) => (

</main>

);}导出异步函数 getStaticProps() {const { 数据 } = 等待 client.query({查询:gql`查询帖子{帖子{边{节点{标题数据库 ID蛞蝓摘录(格式:RENDERED)}}}}`,});如果(data.posts.edges === 0){返回 { notFound: true };}返回 {道具: {帖子:data.posts.edges,},重新验证:10,};}导出默认首页;

然后对于单个帖子页面:

/blog/[slug].js

从next/link"导入链接;import { gql } from "@apollo/client";从../../apollo-client"导入客户端;导出默认函数 BlogPage(props) {const { post } = props;如果(!发布){返回<p>正在加载...</p>;}返回 (<div><h1>{post.title}</h1><div risklySetInnerHTML={{ __html: post.content }}/><Link href="/"><a>&larr;回到家</链接>

);}导出异步函数 getStaticProps({ params }) {const { slug } = 参数;const 结果 = 等待 client.query({查询:gql`查询 GetWordPressPostBySlug($id: ID!) {帖子(id:$ id,idType:SLUG){标题内容}}`,变量:{ id: slug },});如果(!result.data.post){返回 { notFound: true };}返回 {道具: {帖子:result.data.post,},重新验证:10,};}导出异步函数 getStaticPaths() {const 结果 = 等待 client.query({查询:gql`查询 GetWordPressPosts {帖子{节点{蛞蝓}}}`,});返回 {路径: result.data.posts.nodes.map(({ slug }) => {返回 {参数:{ 蛞蝓},};}),后备:真的,};}

添加新帖子时它有效,一旦我删除它,它就不会被删除.在执行 npm run devnpm run build 然后 npm start

时都会发生这种情况

我可能在 ISR 和重新验证的工作方式方面遇到问题.或者我可能在我的代码中遗漏了什么?任何帮助将不胜感激.

-- 编辑 --

同时还有更多线程,这里是 Stackoverflow 和 Next.js github 存储库,与我所经历的相关.相关页面:

Next.js 不删除动态页面删除在内容管理系统中

https://github.com/vercel/next.js/issues/25470

Next.js ISR 页面在CMS中删除后不会被删除

如何清除 NextJs GetStaticPaths 缓存/"取消发布"动态路由?

https://github.com/vercel/next.js/discussions/18967

解决方案

我不确定这是否符合您的用例,但在我参与的其中一个项目中,如果源数据被删除,我们将返回 404.

导出异步函数 getStaticPaths() {//根据帖子获取我们想要预渲染的路径//我们不需要在构建过程中生成任何东西返回 {路径:[],后备:真的,};}导出异步函数 getStaticProps({ params: { slug } }) {//在此处运行您的数据获取代码尝试 {const data = await getData(slug);返回 {道具:{数据,弹头},重新验证:30,未找到:!数据,};}赶上(e){返回 {道具:{数据:空,弹头},重新验证:30,未找到:真实,};}}

文档:https://nextjs.org/blog/next-10#redirect-and-notfound-support-for-getstaticprops--getserversideprops

I am trying out Next.js and build a small app which fetches posts from a headless WordPress app with GraphQL installed. Then I use Apollo/Client to get GraphQL content:

apollo-client.js

import { ApolloClient, InMemoryCache } from "@apollo/client";

const client = new ApolloClient({
  uri: process.env.WORDPRESS_GRAPHQL_ENDPOINT,
  cache: new InMemoryCache(),
});

export default client;

In index I grab the posts:

index.js

import Head from "next/head";
import styles from "../styles/Home.module.css";

import { gql } from "@apollo/client";
import Link from "next/link";
import client from "../apollo-client";

function Home(props) {
  const { posts } = props;
  return (
    <div className={styles.container}>
      <Head>
        <title>Wordpress blog posts</title>
        <meta
          name="description"
          content="Wordpress blog posts with Apollo Client"
        />
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <main className={styles.main}>=
        <div className={styles.grid}>
          {posts.map((post) => (
            <a
              key={post.node.databaseId}
              href={`/blog/${post.node.slug}`}
              className={styles.card}
            >
              <h2>{post.node.title}</h2>
              <div dangerouslySetInnerHTML={{ __html: post.node.excerpt }} />
            </a>
          ))}
        </div>
      </main>
    </div>
  );
}

export async function getStaticProps() {
  const { data } = await client.query({
    query: gql`
      query Posts {
        posts {
          edges {
            node {
              title
              databaseId
              slug
              excerpt(format: RENDERED)
            }
          }
        }
      }
    `,
  });

  if (data.posts.edges === 0) {
    return { notFound: true };
  }

  return {
    props: {
      posts: data.posts.edges,
    },
    revalidate: 10,
  };
}

export default Home;

Then for the single post page:

/blog/[slug].js

import Link from "next/link";
import { gql } from "@apollo/client";
import client from "../../apollo-client";

export default function BlogPage(props) {
  const { post } = props;

  if (!post) {
    return <p>Loading...</p>;
  }

  return (
    <div>
      <h1>{post.title}</h1>
      <div dangerouslySetInnerHTML={{ __html: post.content }} />
      <Link href="/">
        <a>&larr; back to home</a>
      </Link>
    </div>
  );
}

export async function getStaticProps({ params }) {
  const { slug } = params;
  const result = await client.query({
    query: gql`
      query GetWordPressPostBySlug($id: ID!) {
        post(id: $id, idType: SLUG) {
          title
          content
        }
      }
    `,
    variables: { id: slug },
  });

  if (!result.data.post) {
    return { notFound: true };
  }

  return {
    props: {
      post: result.data.post,
    },
    revalidate: 10,
  };
}

export async function getStaticPaths() {
  const result = await client.query({
    query: gql`
      query GetWordPressPosts {
        posts {
          nodes {
            slug
          }
        }
      }
    `,
  });

  return {
    paths: result.data.posts.nodes.map(({ slug }) => {
      return {
        params: { slug },
      };
    }),
    fallback: true,
  };
}

When adding a new post it works, once I delete it, it does not get removed. This happens both when doing npm run dev and npm run build then npm start

I might be getting something wrong here in how ISR and revalidate works. Or I might be missing something in my code? Any help would be appreciated.

-- edit --

Meanwhile there are a couple of more threads, here on Stackoverflow and the Next.js github repository, related to what I'm experiencing. Related pages:

Next.js does not delete dynamic page deleted in CMS

https://github.com/vercel/next.js/issues/25470

Next.js ISR page not being deleted after deleting it in CMS

How to clear NextJs GetStaticPaths cache / "unpublish" a dynamic route?

https://github.com/vercel/next.js/discussions/18967

解决方案

I am not sure if this matches your use-case, but in one of the projects I worked on, if the source data is deleted, we return a 404.

export async function getStaticPaths() {
  // Get the paths we want to pre-render based on posts
  // We do not need to generate anything during build
  return {
    paths: [],
    fallback: true,
  };
}

export async function getStaticProps({ params: { slug } }) {
  // Run your data fetching code here
  try {
    const data = await getData(slug);
    return {
      props: { data, slug },
      revalidate: 30,
      notFound: !data,
    };
  } catch (e) {
    return {
      props: { data: null, slug },
      revalidate: 30,
      notFound: true,
    };
  }
}

Docs: https://nextjs.org/blog/next-10#redirect-and-notfound-support-for-getstaticprops--getserversideprops

这篇关于Next.js ISR页面在CMS中删除后没有被删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆