import { useState, useEffect } from 'react'; import { useDispatch, useSelector } from 'umi'; import { DictionaryModelState } from '@/common/types/connect'; export type DictionaryKey = 'deviceConfig' | 'ruleEngine'; export type DispatchTypeMap = { [type in DictionaryKey]: string; }; export type ReturnValue = [boolean, DictionaryModelState]; const dispatchTypeMap: DispatchTypeMap = { deviceConfig: 'fetchGetDeviceDictionary', ruleEngine: 'fetchRuleEngineConfig' }; const useDictionary = (keys: DictionaryKey[] = ['deviceConfig']): ReturnValue => { // 表示字典是否在加载中 const [loading, setLoading] = useState(false); const dispatch = useDispatch(); const dictionaryState = useSelector((state) => state['dictionary']) || {}; // 根据配置去获取数据字典 useEffect(() => { if (keys.length) { keys.forEach((item) => { const dispatchType = dispatchTypeMap[item]; if (dispatchType && !dictionaryState[item]) { dispatch!({ type: `dictionary/${dispatchType}` }); } }); } }, []); // 判断是否全部请求完毕 useEffect(() => { const results = keys .map((item) => { return dictionaryState[item] !== undefined; }) .filter((item) => item !== true); setLoading(results.length !== 0); }, [dictionaryState]); return [loading, dictionaryState]; }; export default useDictionary;