Просмотр исходного кода

♻️ refactor(areas): 重构区域管理页面数据请求逻辑

- 替换ahooks的useRequest为@tanstack/react-query的useQuery和useMutation
- 实现查询缓存和自动失效机制,提升用户体验
- 创建区域、更新区域和删除区域操作迁移到useMutation实现
- 移除手动调用run刷新数据的逻辑,统一使用queryClient.invalidateQueries
- 优化分页和搜索交互,通过更新pagination触发重新查询
- 增加请求错误处理和状态判断,提高代码健壮性
yourname 9 месяцев назад
Родитель
Сommit
c11dd5efe4
1 измененных файлов с 76 добавлено и 30 удалено
  1. 76 30
      src/client/admin/pages/Areas.tsx

+ 76 - 30
src/client/admin/pages/Areas.tsx

@@ -1,7 +1,7 @@
 import React, { useState, useEffect } from 'react';
 import React, { useState, useEffect } from 'react';
 import { Table, Button, Space, Input, Modal, Form, message } from 'antd';
 import { Table, Button, Space, Input, Modal, Form, message } from 'antd';
 import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined } from '@ant-design/icons';
 import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined } from '@ant-design/icons';
-import { useRequest } from 'ahooks';
+import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
 import { areaClient } from '@/client/api';
 import { areaClient } from '@/client/api';
 import type { InferResponseType } from 'hono/client';
 import type { InferResponseType } from 'hono/client';
 
 
@@ -14,24 +14,32 @@ const Areas: React.FC = () => {
   const [modalVisible, setModalVisible] = useState(false);
   const [modalVisible, setModalVisible] = useState(false);
   const [editingKey, setEditingKey] = useState<string | null>(null);
   const [editingKey, setEditingKey] = useState<string | null>(null);
   const [searchText, setSearchText] = useState('');
   const [searchText, setSearchText] = useState('');
+  const queryClient = useQueryClient();
   
   
   // 获取区域列表数据
   // 获取区域列表数据
-  const { data, loading, run } = useRequest<AreaListResponse>(
-    ({ page, pageSize }: { page: number; pageSize: number }) => areaClient.$get({
-      query: { page, pageSize, keyword: searchText } 
-    }),
-    {
-      refreshDeps: [searchText],
-      defaultParams: [{ page: 1, pageSize: 10 }],
-      onSuccess: (result: AreaListResponse) => {
-        setDataSource(result.data);
-        setPagination({
-          ...pagination,
-          total: result.pagination.total,
-        });
-      },
+  const { data: areasData, isLoading: areasLoading } = useQuery({
+    queryKey: ['areas', pagination.current, pagination.pageSize, searchText],
+    queryFn: async () => {
+      const res = await areaClient.$get({
+        query: {
+          page: pagination.current,
+          pageSize: pagination.pageSize,
+          keyword: searchText
+        }
+      });
+      if (res.status !== 200) {
+        throw new Error('获取区域列表失败');
+      }
+      return res.json() as Promise<AreaListResponse>;
+    },
+    onSuccess: (result) => {
+      setDataSource(result.data);
+      setPagination({
+        ...pagination,
+        total: result.pagination.total,
+      });
     }
     }
-  );
+  });
   
   
   const [dataSource, setDataSource] = useState<AreaItem[]>([]);
   const [dataSource, setDataSource] = useState<AreaItem[]>([]);
   const [pagination, setPagination] = useState({
   const [pagination, setPagination] = useState({
@@ -42,13 +50,12 @@ const Areas: React.FC = () => {
   
   
   // 搜索
   // 搜索
   const handleSearch = () => {
   const handleSearch = () => {
-    run({ page: 1, pageSize: pagination.pageSize });
+    setPagination({ ...pagination, current: 1 });
   };
   };
   
   
   // 分页变化
   // 分页变化
   const handleTableChange = (pagination: any) => {
   const handleTableChange = (pagination: any) => {
     setPagination(pagination);
     setPagination(pagination);
-    run({ page: pagination.current, pageSize: pagination.pageSize });
   };
   };
   
   
   // 显示添加/编辑弹窗
   // 显示添加/编辑弹窗
@@ -72,6 +79,39 @@ const Areas: React.FC = () => {
     form.resetFields();
     form.resetFields();
   };
   };
   
   
+  // 创建区域
+  const createArea = useMutation({
+    mutationFn: async (data: any) => {
+      const res = await areaClient.$post({ json: data as any });
+      if (res.status !== 200) {
+        throw new Error('创建区域失败');
+      }
+      return res.json();
+    },
+    onSuccess: () => {
+      message.success('创建成功');
+      queryClient.invalidateQueries({ queryKey: ['areas'] });
+    }
+  });
+  
+  // 更新区域
+  const updateArea = useMutation({
+    mutationFn: async ({ id, data }: { id: string; data: any }) => {
+      const res = await areaClient[':id'].$put({
+        param: { id: Number(id) },
+        json: data,
+      });
+      if (res.status !== 200) {
+        throw new Error('更新区域失败');
+      }
+      return res.json();
+    },
+    onSuccess: () => {
+      message.success('更新成功');
+      queryClient.invalidateQueries({ queryKey: ['areas'] });
+    }
+  });
+  
   // 提交表单
   // 提交表单
   const handleSubmit = async () => {
   const handleSubmit = async () => {
     try {
     try {
@@ -79,30 +119,36 @@ const Areas: React.FC = () => {
       
       
       if (editingKey) {
       if (editingKey) {
         // 更新操作
         // 更新操作
-        await areaClient[':id'].$put({
-          param: { id: editingKey },
-          json: values,
-        });
-        message.success('更新成功');
+        await updateArea.mutateAsync({ id: editingKey, data: values });
       } else {
       } else {
         // 创建操作
         // 创建操作
-        await areaClient.$post({ json: values });
-        message.success('创建成功');
+        await createArea.mutateAsync(values);
       }
       }
       
       
       setModalVisible(false);
       setModalVisible(false);
-      run({ page: pagination.current, pageSize: pagination.pageSize });
     } catch (error) {
     } catch (error) {
       message.error('操作失败,请重试');
       message.error('操作失败,请重试');
     }
     }
   };
   };
   
   
-  // 删除操作
+  // 删除区域
+  const deleteArea = useMutation({
+    mutationFn: async (id: string) => {
+      const res = await areaClient[':id'].$delete({ param: { id } });
+      if (res.status !== 200) {
+        throw new Error('删除区域失败');
+      }
+      return res.json();
+    },
+    onSuccess: () => {
+      message.success('删除成功');
+      queryClient.invalidateQueries({ queryKey: ['areas'] });
+    }
+  });
+  
   const handleDelete = async (id: string) => {
   const handleDelete = async (id: string) => {
     try {
     try {
-      await areaClient[':id'].$delete({ param: { id } });
-      message.success('删除成功');
-      run({ page: pagination.current, pageSize: pagination.pageSize });
+      await deleteArea.mutateAsync(id);
     } catch (error) {
     } catch (error) {
       message.error('删除失败,请重试');
       message.error('删除失败,请重试');
     }
     }