Graphql 查询错误!变量已声明但从未使用

Muh*_*lha 6 javascript shopify react-native graphql-js react-apollo

我正在尝试根据搜索关键字获取 Shopify 产品。

我通过在查询中传递硬编码值来测试此查询,它工作正常,但我需要传递变量值,因此在这种情况下它会给出错误

Grapghql 查询错误 searchKeyword 已声明但未使用。

这是我根据title,tag和搜索产品的查询product_type

不成功案例:

export const searchProductsQuery = gql` query($searchKeyword: String!){
    shop {
        products(first: 10, query:"title:'$searchKeyword' OR tag:'$searchKeyword' OR product_type:'$searchKeyword'") {
            edges {
                cursor
                node {
                    id
                    title
                    handle
                    description
                    productType
                    images(first: 5) {
                        edges {
                            node {
                                id
                                src
                            }
                        }
                    }
                    variants(first: 5) {
                        edges {
                            node {
                                id
                                title
                                price
                            }
                        }
                    }
                }
            }
        }
    }
}`;
Run Code Online (Sandbox Code Playgroud)

成功案例:

export const searchProductsQuery = gql` query{
shop {
     products(first: 10, query:"title:'games' OR tag:'games' OR product_type:'games'") {
    ...
};
Run Code Online (Sandbox Code Playgroud)

Dan*_*den 4

您为操作定义的变量就是变量。它们不能像模板文字占位符一样使用,而这正是您想要做的。

在 GraphQL 中,变量只能用作参数的输入。例如,query是一个采用(非空)字符串的参数。因此,我们可以创建一个像 一样的变量$mySearchQuery,将其设置为"title:'games' OR tag:'games' OR product_type:'games'",然后像这样使用它:

products(query:$mySearchQuery)
Run Code Online (Sandbox Code Playgroud)

如果您想将 javascript 变量用作 的一部分,则可以使用模板文字$mySearchQuery设置在 javascript 代码中传入的值:$mySearchQuery

const options = {
  variables: {
    mySearchQuery: `title:'${keyword}' OR tag:'${keyword}' OR product_type:'${keyword}'`
  }
}
Run Code Online (Sandbox Code Playgroud)

您看到一个错误,表明您的变量已声明但从未使用过,因为它从未使用过 - 查询中对它的引用是字符串的一部分,因此按字面解析。