我刚刚开始第一次使用 graphql,因为我已将 NEXTJS 应用程序与 Strapi 集成。但我收到了此错误消息Cannot destruct property 'data' of '(intermediate value)'因为它未定义。
我遵循了本教程 - enter link description here
只是将其修改为我想要的。这是我的 graphql:
query {
posts {
data {
attributes {
heading
}
}
}
}
这是我的 vs 代码:
export async function getStaticProps() {
const client = new ApolloClient({
url: 'http://localhost:1337/graphql/',
cache: new InMemoryCache(),
})
const { data } = await client.query({
query: gql`
query {
posts {
data {
attributes {
heading
}
}
}
}
`,
})
return {
props: {
posts: data.posts,
},
}
}
完整代码:
import { ApolloClient, InMemoryCache, gql } from '@apollo/client'
export default function Blog({ posts }) {
console.log('posts', posts)
return (
<div>
{posts.map(post => {
return (
<div>
<p>{posts.heading}</p>
</div>
)
})}
</div>
)
}
export async function getStaticProps() {
const client = new ApolloClient({
url: 'http://localhost:1337/graphql/',
cache: new InMemoryCache(),
})
const { data } = await client.query({
query: gql`
query {
posts {
data {
attributes {
heading
}
}
}
}
`,
})
return {
props: {
posts: data.posts,
},
}
}
我真的不知道从哪里开始。
最佳答案
- 首先检查您是否从 API 接收到空数据。
- 如果是数组,请检查其长度或使用 Array.isArray(myArray) 等方法。
- 如果是对象,则创建一个像这样的函数来检查对象。
function isObjectEmpty(obj) {
return (
!!obj && // 👈 null and undefined check
Object.keys(obj).length === 0 &&
obj.constructor === Object
)
}
export default isObjectEmpty
- 如果数据为空,则返回
notFound
属性为 true 以显示您的 404 页面。
// This function gets called at build time
export async function getStaticProps({ params, preview = false }) {
// fetch posts
// check validity data
return isObjectEmpty(pageData)
? { notFound: true }
: {
props: {
posts
}
}
}
- 其次添加故障安全机制,例如使用
可选链
来安全地访问嵌套值/属性。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
export default function Blog({ posts }) {
console.log('posts', posts)
return (
<div>
{posts?.length && posts?.map(post => {
return (
<div>
<p>{posts?.heading}</p>
</div>
)
})}
</div>
)
}
关于graphql - 无法解构 {intermediate value} 的属性,因为它未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70196230/