reactjs - 如何仅在按钮点击时调用 React 查询 useMutation
我有一个自定义的 useMutation hook,我希望仅在按钮点击时使用这个 mutation。我看到的情况是,mutation 在我挂载组件时就已经运行了,然后在按钮点击时又运行了一次。我希望它 仅在按钮点击时发生。
这是我的自定义 useMutation 钩子:
export const constructOmgevingscheckPostRequest = (coordinates: string) => {
console.log(
'coordinates inside constructOmgevingscheckPostRequest',
coordinates,
);
return {
verzoekAard: 'ARC',
geometrie: coordinates,
};
};
export async function getOmgevingscheckData(coordinates: string) {
console.log('coordinates inside getOmgevingscheckResult', coordinates);
const { data: response } = await omgevingscheckApi.post(
'/rs/v1/omgevingscheck',
constructOmgevingscheckPostRequest(coordinates),
);
return response;
}
export function useOmgevingscheckMutation(coordinates: any) {
return useMutation(['omgevingscheck', { coordinates }], () =>
getOmgevingscheckData(coordinates),
);
}
在我的组件中,我是这样使用它的:
import { useState, useEffect } from 'react';
// import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { type IOmgevingscheckThema } from '../../types/IOmgevingscheckData';
import { Loading } from '@/components/Loading';
import { ErrorAlert } from '@/features/error/components';
import { useOmgevingscheckMutation } from '@/api';
import { usePolygonWktString } from '../../context/PolygonContext';
export function DesktopLayout() {
const [step, setStep] = useState<number>(0);
const { t } = useTranslation('app');
const polygonWktString = usePolygonWktString();
const useMutation = useOmgevingscheckMutation(
polygonWktString?.polygonWktString,
);
const handleOmgevingscheckUitvoeren = () => {
console.log(
'polygonWktString from store',
polygonWktString?.polygonWktString,
);
useMutation.mutate();
setStep(step + 1);
};
useEffect(() => {
if (useMutation.isSuccess) {
// console.log('data', useMutation.data);
}
}, [useMutation.isSuccess, useMutation.isError]);
// if (useMutation.isLoading) {
// console.log('loading');
// }
// if (useMutation.isError) {
// console.log('error');
// }
// console.log('useMutation.error', useMutation.error);
// console.log('step', step);
return (
<>
{useMutation.isLoading && (
// Loading Component
)}
{useMutation.isError ? (
// Error Component
) : null}
{step === 0 && (
<DesktopStepOne
omgevingscheckUitvoeren={handleOmgevingscheckUitvoeren}
isDisabled={polygonWktString?.polygonWktString ? false : true}
/>
)}
{step === 1 && useMutation.isSuccess && (
// Component showing all of the data from the useMutation.data
</div>
)}
</>
);
}
它有点管用,但我遇到的问题/疑问/问题是:
const useMutation=useOmgevingscheckMutation( polygonWktString?.polygonWktString);会在我第一次加载组件时运行,但我希望它在以下情况下运行:当我点击按钮并且有数据时才运行post.request,如果data: null | undefined则不应该运行(可能抛出一个错误?)我不知道我是否在我的组件中处理来自
useMutation的isLoading, isError, isSuccess状态?
摘要:如何仅在按钮点击时处理 useMutation?