You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React项目中GraphQL查询无网络请求问题排查及实现方案

修复GraphQL查询无法触发的问题

以下是你需要修改的关键代码点,按优先级排序:

1. 修正GraphQL查询定义

后端Schema明确getCollectionReportOverview返回的是**String!**(应为PDF的字符串形式,比如base64),但你当前的查询错误地请求了子字段,这会直接导致语法错误,Apollo会拦截请求不发送。同时输入类型名称也写错了,后端是ReportCollectionOverview而非ReportCollectionOverviewInput。

修正后的查询代码:

import { gql } from '@apollo/client';

const GET_COLLECTION_REPORT_OVERVIEW = gql`
  query getCollectionReportOverview($filterReportCollectionOverview: ReportCollectionOverview!) {
    getCollectionReportOverview(filterReportCollectionOverview: $filterReportCollectionOverview)
  }
`;
export { GET_COLLECTION_REPORT_OVERVIEW };

说明:因为返回值是单个字符串,不需要花括号包裹字段列表,直接写查询名即可。

2. 修正变量传递格式

你调用getCollectionReportOverview时,没有按照Schema要求将变量包装在filterReportCollectionOverview对象中,而是直接平铺变量,这会导致变量校验失败,请求无法发送。

修正后的变量传递部分:

getCollectionReportOverview({
  variables: {
    filterReportCollectionOverview: { // 必须将所有输入字段包装在此对象内
      collectionNames: collectionNames,
      collectionNumbers: collectionNumbers,
      brandName: selectedBrands[0]?.brandName,
      createdByName: 'YourCreatedByName',
      createdBy: 'YourCreatedBy', // 注意需传入合法的UUID格式字符串
      sortBy: sortby,
      // 可选字段若不需要可省略,如需补充需严格匹配Schema字段名
    },
  },
  pollInterval: 0,
  fetchPolicy: 'network-only',
  context: { clientName: GraphClientNames['reports'] },
});

3. 移除多余的setTimeout逻辑

你手动添加的setTimeout会强制篡改loading状态,掩盖Apollo真实的请求生命周期,甚至会在请求未完成时就将loading设为false,同时1秒的延迟会让你无法立即看到请求触发。

修正后的点击事件处理函数:

const handleClickCreateViewButton = (): void => {
  setLoading(true);
  // 先校验必填变量是否完整
  if (!selectedBrands[0]?.brandName) {
    console.error('Brand name is required');
    setLoading(false);
    return;
  }
  getCollectionReportOverview({
    variables: {
      filterReportCollectionOverview: {
        collectionNames: collectionNames,
        collectionNumbers: collectionNumbers,
        brandName: selectedBrands[0].brandName,
        createdByName: 'YourCreatedByName',
        createdBy: 'YourCreatedBy',
        sortBy: sortby,
      },
    },
    pollInterval: 0,
    fetchPolicy: 'network-only',
    context: { clientName: GraphClientNames['reports'] },
  });
};

说明:loading状态完全由useLazyQuery的onCompleted和onError回调控制,无需手动设置超时。

4. 额外校验:确保必填变量非空

Schema中brandName是必填项,若selectedBrands[0]?.brandName为空,Apollo会因变量校验失败而不发送请求,所以添加前置校验很有必要。

内容的提问来源于stack exchange,提问作者Jdeveloper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 09:40:59