首页 > 解决方案 > 如果 GraphQL 中的变量为空,我如何跳过查询?

问题描述

如果对象不存在,我试图跳过查询,但它似乎不起作用,我想知道是否有任何解决方案。

这是我的查询

graphql(GET_UBO_DECLARATIONS, {
    name: "getUboDeclarations",
    options: () => ({
      fetchPolicy: "network-only"
    })
  }),
  graphql(GET_UBOS, {
    name: "getUbos",
    skip: props =>
      !props.getUboDeclarations ||
      !props.getUboDeclarations.getUboDeclarationsForThisUser,
    options: props => ({
      fetchPolicy: "network-only",
      variables: {
        _id: props.getUboDeclarations.getUboDeclarationsForThisUser._id
      }
    })
  }),

props.getUboDeclarations.getUboDeclarationsForThisUser返回 null 所以它应该是false并且查询被跳过

标签: graphql

解决方案


问题不在于skip-variables无法保证这些选项的评估顺序,因此即使skip评估为true,该options函数仍可能被调用。如果它被调用并且props.getUboDeclarations.getUboDeclarationsForThisUser实际上是null,你会得到一个 TypeError 因为你试图读取一个值的_id属性。null解决方法是修改variables以考虑可能的空值:

variables: {
  _id: props.getUboDeclarations && props.getUboDeclarations.getUboDeclarationsForThisUser && props.getUboDeclarations.getUboDeclarationsForThisUser_id
}

请注意,您可以使用 lodash 之类的东西get来使这些空保护子句更易于处理。


推荐阅读