【问题标题】:Next js - Can't generate dynamic getStaticPaths with apollo client apiNext js - 无法使用 apollo 客户端 api 生成动态 getStaticPaths
【发布时间】:2021-08-05 14:35:25
【问题描述】:

我不想使用 Apollo graphql 客户端为 next.js 中的 SSG 导出生成我的帖子的 slug 列表。 这是我的代码:

import { gql } from "@apollo/client";
import client from "../../graphql/apollo-client";
import { BLOG_POSTS, POST_DATA } from "../../graphql/apollo-queries";


export async function getStaticPaths() {
   const { loading, error, data } = await client.query({ query: BLOG_POSTS });
   const peths = data.posts.nodes.map((post) => ({
      params: { slug: post.slug },
   }));

   return {
      paths: peths || [],
      fallback: true,
   };
}



export async function getStaticProps({ params }) {
   const { data } = await client.query({
      query: POST_DATA,
      variables: { id: params.slug, idType: "SLUG" },
   });

   return {
      props: {
         post: data.post,
      },
   };
}

export default function BlogSlug({ post }) {
   return (
       <h1>{post.title}</h1>
   )
}

当我使用npm run dev 在开发模式下启动下一个应用程序时,这可以正常工作,但是当我想运行next build &amp;&amp; next export 时,似乎API 不起作用并且data 返回undefined,因此, 没有生成页面并且它抛出一个错误说TypeError: Cannot read property 'title' of undefined

【问题讨论】:

    标签: graphql next.js apollo-client ssg


    【解决方案1】:

    fallback: true 更改为fallback: false 解决了问题。

    来自 Next.js 网站 (https://nextjs.org/docs/messages/prerender-error):

    确保您的组件在启用后处理回退 获取静态路径。

    【讨论】:

      猜你喜欢
      • 2020-10-25
      • 1970-01-01
      • 2019-07-26
      • 1970-01-01
      • 2023-02-22
      • 2021-04-19
      • 2021-07-05
      • 2017-10-23
      • 2022-10-17
      相关资源
      最近更新 更多