【发布时间】:2022-01-08 18:06:21
【问题描述】:
我刚刚开始使用graphql,因为我已经将我的NEXTJS 应用程序与strapi 集成在一起。但我收到了这条错误消息“无法解构‘(中间值)’的属性‘数据’,因为它是未定义的。”
我按照本教程进行操作 - 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,
},
}
}
我真的不知道从哪里开始。
【问题讨论】:
-
我一直在玩它。而且,它没有连接到我的 graphql 并访问数据,因此数组始终为空。
-
代码导出异步函数 getStaticProps() { const client = new ApolloClient({ url: 'localhost:1337/graphql', cache: new InMemoryCache() }); const { stuff } = await client.query ({ query: gql `query GetPosts { posts{ data{ attributes { heading } } } } ` });返回 { 道具: { 帖子: stuff.posts } } }