cur*_*ous 3 apollo graphql react-apollo apollo-client
尝试将嵌套变量传递给 GraphQL 查询,但我的服务器仅获取顶级变量 ( shopId),其他所有内容均为 null。
我试过:
#1
const CALCULATE_PACKAGE_PRICE = gql`
query CalculatePackagePrice(
$shopId: String!
$address1: String
$zip: String
$city: String
$countryCode: String
) {
calculatePackagePrice(
where: {
shopId: $shopId
destination: {
address1: $address1
zip: $zip
city: $city
countryCode: $countryCode
}
}
) {
name
price
userErrors {
field
message
}
}
}
`
const [calculatePackagePrice, { loading, data }] = useLazyQuery(
CALCULATE_PACKAGE_PRICE,
{
variables: {
shopId: shopId,
destination: {
address1: "Example 123",
zip: "123",
city: "Test",
countryCode: "US",
},
},
}
)Run Code Online (Sandbox Code Playgroud)
和#2:
export function CALCULATE_PACKAGE_PRICE({ shopId, destination }) {
return gql`
query CalculatePackagePrice {
calculatePackagePrice(
where: {
shopId: "${shopId}"
destination: {
address1: "${destination.address1}"
zip: "${destination.zip}
city: "${destination.city}"
countryCode: "${destination.countryCode}"
}
}
) {
name
price
userErrors {
field
message
}
}
}
`
}
const [calculatePackagePrice, { loading, data }] = useLazyQuery(
CALCULATE_PACKAGE_PRICE({
shopId: shopId,
destination: {
address1: "Example 123",
zip: "123",
city: "Test",
countryCode: "US",
},
})
)Run Code Online (Sandbox Code Playgroud)
当我将变量内容硬编码到查询中时,它工作得很好。我做错了什么?
这是来自 graphql 文档的有用片段,
所有声明的变量必须是标量、枚举或输入对象类型。因此,如果要将复杂对象传递到字段中,您需要知道服务器上匹配的输入类型。
您正确地将变量作为字符串传递,但随后尝试(也许成功,但我以前从未见过语法)在 gql 模板字符串中创建对象。相反,为目的地和地点创建输入类型。
input WhereInput {
shopId: String!
destination: DestinationInput!
}
input DestinationInput {
address1: String!
zip: String!
city: String!
countryCode: String!
}
Run Code Online (Sandbox Code Playgroud)
然后更改客户端上的查询(并更新服务器定义),
const CALCULATE_PACKAGE_PRICE = gql`
query CalculatePackagePrice($where: WhereInput!) {
calculatePackagePrice(where: $where) {
name
price
userErrors {
field
message
}
}
}
`
Run Code Online (Sandbox Code Playgroud)
然后传递变量,例如
const [calculatePackagePrice, { loading, data }] = useLazyQuery(
CALCULATE_PACKAGE_PRICE,
{
variables: {
where: {
shopId,
destination: {
address1: "Example 123",
zip: "123",
city: "Test",
countryCode: "US",
},
},
}
}
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4505 次 |
| 最近记录: |