组件
文件夹采用大驼峰命名 例如 HelloWorld
组件名采用大驼峰命名 例如 HelloWorld.tsx
入口文件统一命名为 index.ts
, 统一导出
Api 管理
接口定义
在 api/index.ts
中统一导出
根据服务区分文件 api/user.ts
接口函数名采用小驼峰命名 例如 getUserInfoApi
函数入参命名
params 使用 IGetUserInfoApiParams
data 使用 IGetUserInfoApiData
query 使用 IGetUserInfoApiQuery
返回值使用 IGetUserInfoApiResult
Hooks
请求钩子命名 use + 请求方式 + 接口路径 + Query, useGetUserInfoQuery
Query
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| import { useQuery } from '@tanstack/react-query'; import { useMemo } from 'react'; import type { $API_NAME_CASE$ApiParams } from '@/api' import { $API_NAME$Api } from '@/api'; import { isSuccessApi } from '@/utils';
export const use$API_NAME_CASE$QueryQueryKey = 'use$API_NAME_CASE$Query';
export function use$API_NAME_CASE$Query(options?: { params?: $API_NAME_CASE$ApiParams; options?: { enabled?: boolean; }; }) { const { data: response, ...rest } = useQuery({ queryFn: ({ queryKey }) => $API_NAME$Api(queryKey[1]), queryKey: [use$API_NAME_CASE$QueryQueryKey, options?.params] as const, ...options?.options, });
const data = useMemo(() => { if (!isSuccessApi(response)) return; return response.data; }, [response]);
return { response, data, ...rest, }; };
|
Mutation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| import { useMutation } from '@tanstack/react-query'; import { $API_NAME$Api } from '@/api'; import { queryClient } from '@/main'; import { useGet$GET_API_NAME$QueryQueryKey } from '@/hooks/useGet$GET_API_NAME_CASE$Query';
export const use$API_NAME_CASE$Mutation = () => { const { mutateAsync, ...rest } = useMutation({ mutationFn: $API_NAME$Api, onSuccess: () => { void queryClient.invalidateQueries({ queryKey: [useGet$GET_API_NAME_CASE$QueryQueryKey], }); }, });
return [ mutateAsync, { ...rest, }, ] as const; };
|
…待补充