我试图使用NextJS和GraphQL将一些数据从GraphCMS获取到位于pages/writing.js的页面。问题是,不管我做什么,我都会得到像TypeError: Cannot read properties of undefined (reading 'title')这样的错误。
在过去的几个小时里,我一直在努力解决这个问题。所有的指南--无论是书面的还是视频的--都有很大的不同,所以我感觉有点迷茫,没有一个清晰的北方。我总是设法结束这样的指南,但错误总是存在。
当我转到由GraphCMS提供的content链接时,它工作得很好,正如您在下面的屏幕截图中看到的那样。

这就是我的package.json依赖项的样子,以防它与此相关:
"dependencies": {
"framer-motion": "^7.3.6",
"graphql": "^16.6.0",
"graphql-request": "^5.0.0",
"html-react-parser": "^3.0.4",
"moment": "^2.29.4",
"next": "^12.3.1",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},最后,这就是writing.js组件的样子:
import Head from "next/head";
import Header from "../components/home/Header";
import { GraphQLClient, gql } from "graphql-request";
const Writing = ({ posts }) => {
return (
<>
<p>{posts.title}</p>
</>
);
};
export default Writing;
const url =
"[my content api]";
const client = new GraphQLClient(url, {
headers: {
Authorization: `Bearer [my permanent auth token]`,
},
});
const query = gql`
query MyQuery {
postsConnection {
edges {
node {
date
id
slug
title
}
}
}
}
`;
export function GraphQLRequest() {
const getPosts = async () => {
const variables = { title };
const response = await client.request(query, variables);
console.log("RESPONSE FROM GRAPHQL-REQUEST API CALL", response);
};
return {
props: { title },
};
}我希望能就如何解决这个问题提供一些指导。提前谢谢。
发布于 2022-09-23 17:30:02
通过使用阿波罗和GraphQL成功地修复了它。这是最后的代码。希望这能对未来的人有所帮助。我也推荐来自James Quick.com的GraphCMS和GraphQL视频。
import client from "../apolloClient";
import { gql } from "@apollo/client";
export default function Writing(posts) {
return (
<>
</>
);
}
export async function getStaticProps() {
const { data :posts } = await client.query({
query: gql `
query Posts {
posts {
id
slug
title
}
postsConnection {
edges {
node {
content {
raw
}
coverImage {
url
}
date
}
}
}
}
`,
});
console.log(posts);
return{
props: {
posts
}
}
}https://stackoverflow.com/questions/73823059
复制相似问题