Svelte使用Apollo Client调GraphQL报ctx[x].data is undefined如何解决
错误根因
- Contentful GraphQL 请求地址错误,路径中的
/explore是GraphQL Playground的可视化页面地址,不是实际接口请求地址,调用该地址返回的是HTML内容而非JSON格式的GraphQL响应,导致解析不到data字段。 - 模板中直接访问
$data.data.mellunarModaCollection.items,没有处理请求pending阶段的空值状态,请求未返回时$data.data本身就是undefined,直接访问深层属性会触发报错。 - Svelte不存在
{#async}语法,正确的异步处理语法是{#await},语法使用错误也会导致渲染逻辑异常。
解决步骤
- 修正GraphQL请求地址,删除路径中的
/explore,Contentful标准接口格式为https://graphql.contentful.com/content/v1/spaces/{空间ID} - 模板中使用
{#await}语法处理异步请求的加载、成功、失败三个状态,避免空值访问 - 配合可选链运算符
?.和空数组兜底,避免极端场景下的空值报错
修正后完整代码
<script> import { InMemoryCache } from "@apollo/client/core"; import { SvelteApolloClient } from "svelte-apollo-client"; import { gql } from "@apollo/client/core"; const client = new SvelteApolloClient({ // 修正后的请求地址,删除/explore uri: "https://graphql.contentful.com/content/v1/spaces/4x1ftgol5cf4?access_token=VhWS6Pydw4xIoh0-bo2b7ANxmHxj_698UMVpy8JfmkY", cache: new InMemoryCache() }); let dataQuery = client.query(gql` query { mellunarModaCollection { items { sys { id } title price img { url } off } } } `); </script> <ul> {#await $dataQuery} <li>数据加载中...</li> {:then { data }} {#each data.mellunarModaCollection?.items || [] as item} <li> <h2>{item.title}</h2> <h4>{item.price}</h4> {#if item.img?.url} <img src={item.img.url} alt={item.title} /> {/if} </li> {/each} {:catch error} <li>请求失败:{error.message}</li> {/await} </ul> <style> </style>
内容的提问来源于stack exchange,提问作者mellunar
相关产品推荐
相关产品推荐

