【问题标题】:TypeError: Cannot read properties of null (reading 'title') - Graphcms - NextJsTypeError:无法读取 null 的属性(读取“标题”)-Graphcms-NextJs
【发布时间】:2022-06-19 22:08:36
【问题描述】:

在使用 graphCMS 作为后端的 Next Js 上,当我尝试从服务器获取 [slug].js 中单个项目页面的数据时,我收到此错误。但是它使用 .map 方法在 index.js 文件中工作的同一个项目。

SS of the error

import { GraphQLClient, gql } from "graphql-request";

const graphcms = new GraphQLClient(
  "api url here"
);

const QUERY = gql`
  query Project($slug: String!) {
    project(where: { slug: $slug }) {
      id
      slug
      title
    }
  }
`;

export const SLUGLIST = gql`
  {
    projects {
      slug
    }
  }
`;

export async function getStaticProps({ params }) {
  const slug = params.slug;

  const data = await graphcms.request(QUERY, { slug });

  const project = data.project;

  return {
    props: {
      project,
    },
  };
}

export async function getStaticPaths() {
  const { projects } = await graphcms.request(SLUGLIST);

  return {
    paths: projects.map((project) => ({ params: { slug: project.slug } })),
    fallback: "blocking",
  };
}

export default function Project({ project }) {
  return (
    <div>
      <h1>This is single project page</h1>
      {/* Project container */}
      <div>
          <div>
            <h1>{project.title}</h1>
          </div>
    </div>
  );
}

【问题讨论】:

    标签: next.js graphql graphcms


    【解决方案1】:

    据我所知,您的 GraphQL 客户端尚未配置为工作,因为您的 API url 为“api url here”。对我来说,使用这些设置找不到项目是有道理的。

    考虑捕获项目未定义的情况。您可以在页面中使用类似这样的方式执行此操作。

    if (!project) {
      return <> Project not found </>
    }
    

    或者在原代码中是这样的:

    <h1>{project?.title || "project title not found"}</h1>
    

    【讨论】:

      猜你喜欢
      • 2020-01-29
      • 2022-11-20
      • 2018-09-12
      • 1970-01-01
      • 2022-01-12
      • 2021-12-04
      • 2021-12-17
      • 2022-01-09
      • 1970-01-01
      相关资源
      最近更新 更多