因此,我试图使用阿波罗GraphQL和React通过其ID获取特定的产品数据,但它似乎是返回未定义的。我读了阿波罗的文档并进行了研究,所以我不知道我做错了什么。此外,我还可以从其他不需要ID的查询中返回数据(例如,与所有产品一样)。会非常感谢您的帮助!
查询
export const PRODUCT = gql`
query GetProduct($itemID: String!) {
product(id: $itemID) {
id
name
inStock
gallery
description
category
attributes {
id
name
type
items {
displayValue
value
}
}
prices {
currency {
label
symbol
}
}
brand
}
}
`;--这是我尝试使用ID返回数据的地方,但没有结果:
let myID = "ps-5";
const { productLoading, productError, productData } = useQuery(PRODUCT, {
variables: { itemID: myID },
});
useEffect(() => {
if (productData) {
console.log("data: " + productData) // logs nothing. "Undefined" when if statement is removed
}
}, [])发布于 2022-06-24 12:15:01
看起来阿波罗的React对useQuery使用的API与Vue使用的API相同(我对Vue比较熟悉),在这种情况下,应该像这样使用它:
useQuery(PRODUCT, { itemID: myID })(不是{ variables : { itemID : myID }})
但是,我希望后端返回一个错误,因为$itemID被声明为非空。
发布于 2022-06-24 15:06:24
似乎您正在用错误的对象键破坏useQuery()返回的对象。
// instead of
const { productLoading, productError, productData } = '...'
// you can either use the regular keys as variables
const { loading, error, data } = '...'
// or assign aliases (useful when you use more queries on the same page)
// this way you can use the same variables as in your example
const { loading:productLoading, error:productError, data:productData } = '...'https://stackoverflow.com/questions/72743757
复制相似问题