3.8 KiB
3.8 KiB
| name | description |
|---|---|
| jjb-dict-hooks | 定义 JJB 字典数据获取规范。在使用 http.Get、Hooks 获取字典或 useUserStatusDict 时使用。字典接口不使用 declareRequest。 |
接口与数据层规范
字典数据获取规范
-
统一使用 Hooks 方式获取字典数据:
-
实现流程:
- 在
src/api/<namespace>/index.js中定义字典数据接口(使用传统http.Get()、http.Post()等方式,不使用declareRequest) - 在
src/hooks/中创建对应的数据 Hook - 在页面/组件中使用 Hook 获取字典数据
- 在
-
接口定义示例(在
src/api/dict/index.js中):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中):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 }; }; -
使用示例(在页面/组件中):
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 中实现缓存逻辑)
- 字典数据接口不使用
-