♻️ refactor: refactor the logic of fetchTokenKeys and SetupCheck
This commit is contained in:
32
web/src/hooks/useSetupCheck.js
Normal file
32
web/src/hooks/useSetupCheck.js
Normal file
@@ -0,0 +1,32 @@
|
||||
import { useContext, useEffect } from 'react';
|
||||
import { useLocation } from 'react-router-dom';
|
||||
import { StatusContext } from '../context/Status';
|
||||
|
||||
/**
|
||||
* 自定义Hook:检查系统setup状态并进行重定向
|
||||
* @param {Object} options - 配置选项
|
||||
* @param {boolean} options.autoRedirect - 是否自动重定向,默认true
|
||||
* @param {string} options.setupPath - setup页面路径,默认'/setup'
|
||||
* @returns {Object} 返回setup状态信息
|
||||
*/
|
||||
export function useSetupCheck(options = {}) {
|
||||
const { autoRedirect = true, setupPath = '/setup' } = options;
|
||||
const [statusState] = useContext(StatusContext);
|
||||
const location = useLocation();
|
||||
|
||||
const isSetupComplete = statusState?.status?.setup !== false;
|
||||
const needsSetup = !isSetupComplete && location.pathname !== setupPath;
|
||||
|
||||
useEffect(() => {
|
||||
if (autoRedirect && needsSetup) {
|
||||
window.location.href = setupPath;
|
||||
}
|
||||
}, [autoRedirect, needsSetup, setupPath]);
|
||||
|
||||
return {
|
||||
isSetupComplete,
|
||||
needsSetup,
|
||||
statusState,
|
||||
currentPath: location.pathname
|
||||
};
|
||||
}
|
||||
30
web/src/hooks/useTokenKeys.js
Normal file
30
web/src/hooks/useTokenKeys.js
Normal file
@@ -0,0 +1,30 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { fetchTokenKeys, getServerAddress } from '../helpers/token';
|
||||
import { showError } from '../helpers';
|
||||
|
||||
export function useTokenKeys(id) {
|
||||
const [keys, setKeys] = useState([]);
|
||||
const [serverAddress, setServerAddress] = useState('');
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
const loadAllData = async () => {
|
||||
const fetchedKeys = await fetchTokenKeys();
|
||||
if (fetchedKeys.length === 0) {
|
||||
showError('当前没有可用的启用令牌,请确认是否有令牌处于启用状态!');
|
||||
setTimeout(() => {
|
||||
window.location.href = '/token';
|
||||
}, 1500); // 延迟 1.5 秒后跳转
|
||||
}
|
||||
setKeys(fetchedKeys);
|
||||
setIsLoading(false);
|
||||
|
||||
const address = getServerAddress();
|
||||
setServerAddress(address);
|
||||
};
|
||||
|
||||
loadAllData();
|
||||
}, []);
|
||||
|
||||
return { keys, serverAddress, isLoading };
|
||||
}
|
||||
Reference in New Issue
Block a user