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

♻️ refactor(clients): 优化客户管理页面代码逻辑

- 将HTTP响应状态判断从`status !== 200`统一改为更语义化的`!res.ok`
- 重构区域数据处理逻辑,使用useEffect替代query的onSuccess回调
- 为客户列表请求添加明确的类型转换`as Promise<ClientListResponse>`
- 删除客户请求中移除id.toString()转换,直接使用数字类型id
- 将按钮加载状态判断从isLoading改为isPending,更符合React Query最佳实践
yourname 8 месяцев назад
Родитель
Сommit
8d98956290
1 измененных файлов с 15 добавлено и 11 удалено
  1. 15 11
      src/client/admin/pages/Clients.tsx

+ 15 - 11
src/client/admin/pages/Clients.tsx

@@ -31,15 +31,19 @@ const Clients: React.FC = () => {
     queryKey: ['areas'],
     queryFn: async (): Promise<InferResponseType<typeof areaClient.$get, 200>> => {
       const res = await areaClient.$get({ query: { page: 1, pageSize: 1000 } });
-      if (res.status !== 200) {
+      if (!res.ok) {
         throw new Error('获取区域列表失败');
       }
       return res.json();
-    },
-    onSuccess: (data) => {
-      setAreas(data.data);
     }
   });
+
+  // 处理区域数据
+  useEffect(() => {
+    if (areasData?.data) {
+      setAreas(areasData.data);
+    }
+  }, [areasData]);
   
   // 获取客户列表数据
   const { data: clientsData, isLoading: clientsLoading, error: clientsError } = useQuery({
@@ -52,10 +56,10 @@ const Clients: React.FC = () => {
           keyword: searchText
         }
       });
-      if (res.status !== 200) {
+      if (!res.ok) {
         throw new Error('获取客户列表失败');
       }
-      return res.json();
+      return res.json() as Promise<ClientListResponse>;
     }
   });
   
@@ -122,7 +126,7 @@ const Clients: React.FC = () => {
   const createClient = useMutation({
     mutationFn: async (data: any) => {
       const res = await clientClient.$post({ json: data as any });
-      if (res.status !== 200) {
+      if (!res.ok) {
         throw new Error('创建客户失败');
       }
       return res.json();
@@ -140,7 +144,7 @@ const Clients: React.FC = () => {
         param: { id: Number(id) },
         json: data,
       });
-      if (res.status !== 200) {
+      if (!res.ok) {
         throw new Error('更新客户失败');
       }
       return res.json();
@@ -177,8 +181,8 @@ const Clients: React.FC = () => {
   // 删除客户
   const deleteClient = useMutation({
     mutationFn: async (id: number) => {
-      const res = await clientClient[':id'].$delete({ param: { id: id.toString() } });
-      if (res.status !== 200) {
+      const res = await clientClient[':id'].$delete({ param: { id } });
+      if (!res.ok) {
         throw new Error('删除客户失败');
       }
       return res.json();
@@ -331,7 +335,7 @@ const Clients: React.FC = () => {
           <Button key="cancel" onClick={handleCancel}>
             取消
           </Button>,
-          <Button key="submit" type="primary" onClick={handleSubmit} loading={editingKey ? updateClient.isLoading : createClient.isLoading}>
+          <Button key="submit" type="primary" onClick={handleSubmit} loading={editingKey ? updateClient.isPending : createClient.isPending}>
             确定
           </Button>,
         ]}