reactjs - 如何基于 GraphQL API 的 slug 使用 Next.js 进行动态路由?

标签 reactjs graphql next.js apollo apollo-client

我很难理解基于变量的动态路由。我能够获取集合中的项目列表,但不能通过 Next.js 获取具有动态路由的单个页面的单个项目及其字段。
背景
我有一个带有 GraphQL API 的 KeystoneJS headless CMS。我正在尝试创建一个简单的博客,其中包含一个帖子列表和一个单独的帖子页面。我已经能够查询并返回一个帖子列表,但我需要根据 slug 字段获取一个单独的帖子,以便可以在 /posts/[slug].js 访问它。 .
我试过的
我一直在使用 Apollo Client 来处理查询。我有一个 apolloClient.js连接到 API 的文件:

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

export default new ApolloClient({
  uri: "http://localhost:3000/admin/api",
  cache: new InMemoryCache(),
});
我有一个 post.service.js用于查询 API 的文件:
// post.service.js
import { gql } from "@apollo/client";
import apolloClient from "../_utils/apolloClient";

export async function getAll() {
  return apolloClient
    .query({
      query: gql`
        query {
          allPosts {
            id
            term
            slug
          }
        }
      `,
    })
    .then((result) => result.data.allPosts);
}

export async function getBySlug(slug) {
  return apolloClient
    .query({
      query: gql`
        query {
          Post(slug: $slug) {
            id
            title
            lead
            body
          }
        }
      `,
    })
    .then((result) => {
      return result.data.Post;
    });
}
最后,在 posts/[slug].js我正在尝试像这样返回数据:
//[slug].js
import Head from "next/head";
import { ApolloClient, InMemoryCache, gql } from "@apollo/client";
import { getAll, getBySlug } from "../../_services/post.service";

export default function Post({ post }) {
  return (
    <div>
      <Head>
        <title>Launchpad</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <main>
        <h1>{post.term}</h1>
      </main>
      <footer>
        <p>{post.lead}</p>
      </footer>
    </div>
  );
}

export async function getStaticPaths() {
  const posts = await getAll();

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

  return { paths, fallback: false };
}

export async function getStaticProps({ params }) {
  const post = await getBySlug(params.id);

  return { props: { post } };
}
显然,这行不通。我一定不能将变量(我假设是 slug)正确地传递到查询中,并且在阅读了几个教程后我仍然无法理解它。有没有人看到我做错了什么?

最佳答案

getStaticPaths params 中返回的键对象需要匹配动态路由命名。就您而言,因为您使用的是 posts/[slug].js对于路线,您需要返回 params格式为 { slug: post.slug } .

export async function getStaticPaths() {
  const posts = await getAll();

  const paths = posts.map((post) => ({
    params: { slug: post.slug }, // Rename to `slug`
  }));

  return { paths, fallback: false };
}

export async function getStaticProps({ params }) {
  const post = await getBySlug(params.slug); // Rename to `params.slug`

  return { props: { post } };
}
编辑:关于请求问题,以下更改为getBySlug应该让它按预期工作。
export async function getBySlug(slug) {
  return apolloClient
    .query({
      query: gql`
        query Post($slug: String){
          post(slug: $slug) {
            id
            title
            lead
            body
          }
        }
      `,
      variables: {
        slug
      }
    })
    .then((result) => {
      return result.data.Post;
    });
}

关于reactjs - 如何基于 GraphQL API 的 slug 使用 Next.js 进行动态路由?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65819076/

相关文章:

reactjs - 找不到模块 : Error: Can't resolve '@material-ui/core/styles' (when deploying to heroku)

node.js - 如何为 socket io 和 graphql 建立连接?

reactjs - 加载组件出现在页面顶部

next.js - 模块解析失败 : Identifier 'NextResponse' has already been declared (3:6) Middleware. ts(NextJs)

node.js - 与 Hasura 的 WebSocket 连接不适用于 Node.js 上的 ApolloClient v3

javascript - next.js 应用程序的 vscode 启动配置

javascript - 从 React Component 关闭 React Modal

javascript - 如何正确设置 Gatsby.js 主页?

javascript - 为什么 node.js 无法定位其他 typescript React 组件

javascript - GraphQL - 将非特定对象的对象作为参数传递