【问题标题】:using variables in gql apollo query在 gql apollo 查询中使用变量
【发布时间】:2022-01-05 09:46:08
【问题描述】:

我有这个搜索某个产品的 gql 查询,但是这个 ID 是硬编码的 如何用变量替换此 ID (product(id: "apple-imac-2021"))

const CURRENT_PRODUCT = gql`
    query {
        product(id: "apple-imac-2021") {
            name
            inStock
            gallery
            description
            brand
            attributes {
                name
                type
                items {
                    value
                }
            }
            prices {
                currency {
                    label
                    symbol
                }
                amount
            }
        }
    }
`;

【问题讨论】:

标签: reactjs apollo gql


【解决方案1】:

基于这个例子:

这就是解决方案,您应该在查询中执行以下操作:

query product($id : String!) {
        product(id: $id) {
            name
            inStock
            gallery
            description
            brand
            attributes {
                name
                type
                items {
                    value
                }
            }
            prices {
                currency {
                    label
                    symbol
                }
                amount
            }
        }
    }
    `;

然后在使用 useQuery() 时分配 $id 变量:

    const { loading, data } = useQuery(CURRENT_PRODUCT, {
        variables: {
            id: id,
        },
    });

【讨论】:

    猜你喜欢
    • 2020-08-01
    • 2020-01-06
    • 2021-04-19
    • 2018-03-02
    • 2019-02-10
    • 2020-02-02
    • 2020-06-07
    • 2019-01-02
    • 2018-09-25
    相关资源
    最近更新 更多