Skip to main content

字典 Dictionary

该模块提供统一的静态与动态字典定义入口,可用于下拉框、状态映射、表格标签渲染等场景。


💡 使用示例

1. 📚 App.jsx 内初始化字典

import React, { useLayoutEffect } from 'react';

import { initDictData } from '@npmqg/utils-dictionary-data';

import { useGlobalStore } from '@/store';

function AppIndex() {
const setState = useGlobalStore((state) => state.setState);

//初始化
useLayoutEffect(() => {
//初始化字典项
initDictData(require.context('@/dictionary', false, /\.js$/), setState, useGlobalStore.getState).then();
}, []);

return <Routers />;
}

📚 2. 配置字典

src/dictionary/system.js

import { requestAigcModelVendors } from '@/services/public';

const Dict = {
DictPublicMap: {},
//(静态字典、动态字典正反向Map自动生成 所以不需要手动添加)
//静态字典
DictStatic: {
//是否
SystemWhetherOrNot: () => [
{
label: '是',
value: 1,
},
{
label: '否',
value: 0,
},
],
},
//动态字典
DictDynamic: {
SystemImgModel: async () => {
//调用字典接口
const res = await requestAigcModelVendors();

if (!res?.data) return [];

return res?.data?.map((item) => ({
label: item.Title,
value: item.Key,
desc: item.Msg,
icon: 'thinkDeep',
}));
},
},
};

export default Dict;

📚 结合表单项使用 只需传入对应字典名字即可

<FormField
control={form.control}
name="status"
render={({ field }) => (
<FormItem>
<FormLabel>{Intl.v('状态')}</FormLabel>
<FormControl>
{/* 渲染一个是否的下拉框 */}
<FormComponents init="SystemWhetherOrNot" type="select" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>

📚 js 获取对应值 可用于渲染表格 和 查看详情页

import { Dict } from '@npmqg/utils-dictionary-data';

//表头
const columns = useRef([
{
header: '状态',
size: 200,
accessorKey: 'status',
cell: ({ getValue }) => {
const txt = getValue();
const dict = Dict();

//通过原始定义获取 color 字段值
const color = dict?.['SystemUserStatus']?.find?.((item) => item.value === txt)?.color || '';

//通过 动态生成的Map+已知的value 获取 label
const label = dict?.['SystemUserStatusMap']?.get?.(txt) || txt;

return <span className={color}>{label}</span>;
},
},
]);

🧠 设计思路

  • 静态字典:前端预定义的字典项,项目发布后值不可更改 (如需改变需要更新网页)
  • 动态字典:字典存储在后端,配置好后刷新页面自动获取并整理
  • 字典对象内可以写任何自定义字段,放便后续渲染 比如添加 desc 描述、icon 图标、color 颜色...
  • 字典填写完毕后调试或线上运行时会自动生成对应 正反向 Map (可以通过 1 找到 '是'; 也可通过 '是' 找到 1)