NEXTJS集成Strapi用GraphQL时报Cannot destructure错误如何解决?
问题解决方案
该报错本质是client.query()执行异常返回了undefined,导致尝试解构data属性失败,常见原因和对应修复方案如下:
1. 修复Apollo Client初始化参数错误
Apollo Client 构造函数的服务地址配置项为uri而非url,参数名写错会导致客户端无法正常发起请求:
// 错误写法 const client = new ApolloClient({ url: 'http://localhost:1337/graphql/', cache: new InMemoryCache(), }) // 正确写法 const client = new ApolloClient({ uri: 'http://localhost:1337/graphql/', cache: new InMemoryCache(), })
2. 修复返回数据结构适配问题
你当前的GraphQL查询返回的结构如下:
{ "data": { "posts": { "data": [ {"attributes": {"heading": "xxx"}}, ... ] } } }
直接把data.posts传给组件,拿到的是包含data字段的对象而非数组,调用map会报错,建议修改getStaticProps的返回值:
return { props: { posts: data.posts.data, // 直接把数组传给组件 }, }
3. 修复组件渲染逻辑错误
你当前循环体内错误使用了外层的posts变量,且没有取到attributes下的字段:
// 错误写法 {posts.map(post => { return ( <div> <p>{posts.heading}</p> </div> ) })} // 正确写法 {posts.map(post => { return ( <div key={post.id}> {/* 加上循环唯一key避免React警告 */} <p>{post.attributes.heading}</p> </div> ) })}
4. 检查Strapi侧配置
- 确认本地Strapi服务已经启动,且运行在1337端口
- 进入Strapi后台 -> 设置 -> 用户与权限插件 -> 角色 -> Public,勾选Posts集合的
find权限,保存后重试
5. 增加错误捕获方便排查
建议给请求逻辑加上try catch,打印具体的错误信息,方便定位其他可能的网络、跨域、权限问题:
修正后完整代码
import { ApolloClient, InMemoryCache, gql } from '@apollo/client' export default function Blog({ posts }) { console.log('posts', posts) return ( <div> {posts.map(post => { return ( <div key={post.id}> <p>{post.attributes.heading}</p> </div> ) })} </div> ) } export async function getStaticProps() { const client = new ApolloClient({ uri: 'http://localhost:1337/graphql/', cache: new InMemoryCache(), }) try { const { data } = await client.query({ query: gql` query { posts { data { id attributes { heading } } } } `, }) return { props: { posts: data.posts.data, }, } } catch (err) { console.error('GraphQL请求错误:', err) return { props: { posts: [] } } } }
内容的提问来源于stack exchange,提问作者someone
相关产品推荐
相关产品推荐

