【发布时间】:2021-04-20 02:57:18
【问题描述】:
使用React,react-apollo,我有一个向服务器发送一堆值的突变,服务器返回OK或NOT OK。
我想仅在操作时更新值,但为此,我需要在 OnComplete 回调中访问有效负载。
例如:
const [updateCardRate] = useMutation<UpdateInfluencerRateCard, UpdateInfluencerRateCardVariables>(UPDATE_CARD_RATE, {
onCompleted: (e) => {
// Can I have the variables (not just the response) here ?
},
});
const handlePriceChange = async (socialAccountType: SocialMediaTypeForRateCard, price: number) => {
await updateCardRate({ variables: { input: { price, socialAccountType } } });
};
return (<button onClick(SocialMediaTypeForRateCard.FACEBOOK, 122) />
如果没有像使用状态这样的“棘手”方式,这似乎是不可能的?
编辑:尝试使用状态,但不起作用,状态为空:
const [getPayload, setPayload] = useState<any>(null);
const [prices, setPrices] = useState<any>(priceCards);
const [updateCardRate] = useMutation<UpdateInfluencerRateCard, UpdateInfluencerRateCardVariables>(UPDATE_CARD_RATE, {
onError: useCallback((error: ApolloError) => {
enqueueSnackbar(t(error.message || 'UnexpectedError'), { variant: 'error' });
setPrices(priceCards);
}, []),
onCompleted: useCallback(() => {
console.log(getPayload); // this is null
}, []),
});
const handlePriceChange = (socialAccountType: SocialMediaTypeForRateCard, price: number) => {
setPayload({ price, socialAccountType }); // but it s set here
updateCardRate({
variables: { input: { price, socialAccountType } },
});
};
【问题讨论】:
-
onCompleted回调不提供variables作为参数。所以,我想,一个存储变量对象的简单状态应该可以完成这项工作。 -
我试过了,但是当我存储状态,然后在 OnComplete 中使用它时,状态仍然设置为以前的值,因为我猜组件在调用/响应过程中没有更新。
-
顺便说一句,我正在使用
onCompleted: useCallback(() => { }, []), -
1.你不需要
async,awaitonhandlePriceChange, 2. 即使你这样做了,你也需要在调用突变之前设置状态 -
如果您使用回调,请确保状态是它的依赖项。
标签: reactjs graphql react-apollo