微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ApolloClient - 如何传递数组而不是字符串?

如何解决ApolloClient - 如何传递数组而不是字符串?

在 GraphQL Playground 上,此查询有效,因此后端很好:

query ($CatIDs: [String]) {
  categories(where: { id: $CatIDs }) {
    id
  Name
  slug
    collections {
    id
    slug
    Name
    Description
    }
  }
}

变量 $CatIDs 在哪里:

["7","9","13","14"]

现在在我与 NextJS/React 一起使用的 ApolloClient 中,我以这种方式传递数组:

   const { data: SubCategory } = await client.query({
    query: getSubCategories,variables: {
      CatIDs
  },});

问题是,当我在 ApolloClient 中执行此操作时,我认为 CatID 被包裹在额外的引号中,使其成为字符串?

或者可能是什么问题?

错误

ApolloError: select不同的“categories”.* from “categories” where (("categories"."id" = $1)) 和 ("categories"."published_at" 不是 null) 限制 $2 - 整数类型的无效输入语法: "["7","14"]"

编辑:

我现在看到当我手动设置数组时,我得到了有效的响应。

 variables: {
      CatIDs: ["1","2","3"]
  },

所以当我设置 CatID 时一定有问题,即使当我记录它时,该值看起来不错。

这是我设置 CatID 的方式:

  1. 初始响应对象:
  { __typename: 'Category',id: '7' },{ __typename: 'Category',id: '9' },id: '13' },id: '14' }
  1. 映射 ID:
var CatIDs = SubCatIDs.map (x => x.id);

[ '7','9','13','14' ]

  1. JSON.stringify 以获得双引号:
CatIDs = JSON.stringify(CatIDs);

["7","14"]

  1. 使用 CatID 查询 -> 错误

解决方法

解决方案:

  1. 不需要 JSON.stringify
  2. 变量中的第一个条目需要用双引号括起来
const { data: SubCategory } = await client.query({
    query: getSubCategories,variables: {
      "CatIDs": CatIDs
    },});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。