入口文件
import ReactDOM from 'react-dom';
import { QueryClientProvider } from 'react-query';
import { ReactQueryDevtools } from 'react-query/devtools';
import { queryClient } from './query-client.ts';
const App = () => {
return (
<QueryClientProvider client={queryClient}>
{/* AntDesign i18n 基础方案 https://ant.design/docs/react/i18n-cn */}
<Routes />
{/* 可选 ReactQuery 开发工具(生产环境不会渲染) https://react-query.tanstack.com/devtools */}
<ReactQueryDevtools initialIsOpen={false} buttonPosition="bottom-left" />
</QueryClientProvider>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
queryClient 配置文件 query-client.ts
import { QueryCache, QueryClient } from 'react-query';
// import { message } from 'antd';
// 失败 Retry 默认次数
export const RETRY_TIMES = 0;
// 数据 Query 重置请求「翻新」时间
// export const STALE_TIME = 5 * 60 * 1000;
export const STALE_TIME = 0;
/**
* ReactQuery
* React Query is often described as the missing data-fetching library for React, but in more technical terms,
* it makes fetching, caching, synchronizing and updating server state in your React applications a breeze.
* @doc https://react-query.tanstack.com/overview
* @notice 用好 ReactQuery 可以提升应用性能并且提升代码优雅度
*/
const queryClient = new QueryClient({
queryCache: new QueryCache({
onError: (error, query) => {
// message.error(query?.meta?.errorMessage ? `请求失败:${query.meta.errorMessage}` : '请求失败');
console.log(error);
}
}),
defaultOptions: {
queries: {
refetchOnWindowFocus: false,
staleTime: STALE_TIME,
retry: RETRY_TIMES,
// onError: toastErrorMsg,
// select: selectData,
},
mutations: {
// onError: toastErrorMsg,
},
},
});
export { queryClient };
useQuery
const { data, isLoading, refetch } = useQuery(
['queryList', id],
() => fetchList(id),
{
enabled: !!id,
onSuccess: (data) => {
}
}
);
useMutation
const addListM = useMutation(
(config) => addList(config),
{
onSuccess: (data) => {
message.success('增加成功');
refetch();
}
}
);
const add = () => {
addListM.mutate(ListForm.getFieldsValue());
};