safety-eval-service-frontend/.cursor/skills/specs/11-接口与数据层规范/05-字典数据获取规范/SKILL.md

124 lines
3.8 KiB
Markdown
Raw Permalink Normal View History

2026-08-14 16:54:03 +08:00
---
name: jjb-dict-hooks
description: 定义 JJB 字典数据获取规范。在使用 http.Get、Hooks 获取字典或 useUserStatusDict 时使用。字典接口不使用 declareRequest。
---
# 接口与数据层规范
## 字典数据获取规范
- **统一使用 Hooks 方式获取字典数据**
- **实现流程**
1.`src/api/<namespace>/index.js` 中定义字典数据接口(使用传统 `http.Get()`、`http.Post()` 等方式,**不使用 `declareRequest`**
2.`src/hooks/` 中创建对应的数据 Hook
3. 在页面/组件中使用 Hook 获取字典数据
- **接口定义示例**(在 `src/api/dict/index.js` 中):
```javascript
import { http } from '@cqsjjb/jjb-common-lib';
// 获取用户状态字典
export const getUserStatusDict = () => {
return http.Get('/api/dict/user-status');
};
// 获取部门列表字典
export const getDepartmentDict = () => {
return http.Get('/api/dict/department');
};
```
- **Hook 定义示例**(在 `src/hooks/useDict.js` 中):
```javascript
import { useState, useEffect } from 'react';
import { getUserStatusDict, getDepartmentDict } from '~/api/dict';
// 用户状态字典 Hook
export const useUserStatusDict = () => {
const [options, setOptions] = useState([]);
const [loading, setLoading] = useState(false);
useEffect(() => {
const fetchDict = async () => {
setLoading(true);
try {
const res = await getUserStatusDict();
setOptions(res.data || []);
} catch (error) {
console.error('获取用户状态字典失败:', error);
} finally {
setLoading(false);
}
};
fetchDict();
}, []);
return { options, loading };
};
// 部门列表字典 Hook
export const useDepartmentDict = () => {
const [options, setOptions] = useState([]);
const [loading, setLoading] = useState(false);
useEffect(() => {
const fetchDict = async () => {
setLoading(true);
try {
const res = await getDepartmentDict();
setOptions(res.data || []);
} catch (error) {
console.error('获取部门字典失败:', error);
} finally {
setLoading(false);
}
};
fetchDict();
}, []);
return { options, loading };
};
```
- **使用示例**(在页面/组件中):
```javascript
import React from 'react';
import { Select } from 'antd';
import { useUserStatusDict, useDepartmentDict } from '~/hooks/useDict';
function UserForm() {
// 使用 Hook 获取字典数据
const { options: statusOptions, loading: statusLoading } = useUserStatusDict();
const { options: deptOptions, loading: deptLoading } = useDepartmentDict();
return (
<Form>
<Form.Item name="status" label="用户状态">
<Select
showSearch
placeholder="请选择用户状态"
allowClear
loading={statusLoading}
options={statusOptions}
/>
</Form.Item>
<Form.Item name="department" label="所属部门">
<Select
showSearch
placeholder="请选择部门"
allowClear
loading={deptLoading}
options={deptOptions}
/>
</Form.Item>
</Form>
);
}
```
- **注意事项**
- 字典数据接口**不使用 `declareRequest`**,使用传统的 `http.Get()`、`http.Post()` 等方式
- Hook 中需要处理 loading 状态和错误处理
- 字典数据可以缓存,避免重复请求(可在 Hook 中实现缓存逻辑)