温华: 迁移路由请求和用户信息请求到路由拦截处

This commit is contained in:
wenhua
2023-10-16 14:26:37 +08:00
parent 730b12c2e4
commit 60788d7090

View File

@@ -1,6 +1,9 @@
import { Navigate } from "react-router-dom"
import Notfound from "../Notfound"
import { getToken } from "../utils/auth"
import { useDispatch, useSelector } from "react-redux"
import { addRoutes, getAsyncRouters } from "../stores/permission"
import { addAuthInfo, getAuthInfo } from "../stores/auth"
const Views = import.meta.glob('../view/**/*.tsx')
// 判断是否有对应路径的映射文件
@@ -13,17 +16,35 @@ const hasMapFile = (filePath: string): boolean => {
* @description 路由拦截组件
* @param {children: ReactDOM, filePath: string(文件路径)}
*/
export default function RouteInterception ({children, filePath=""}: any) {
if(getToken()) {
if(filePath!=="") {
if(hasMapFile(filePath)) {
return children
} else {
return <Notfound />
export default function RouteInterception({ children, filePath = "" }: any) {
const routes: [] = useSelector((store: any) => store.permission)
const dispatch = useDispatch()
const requestAsyncRoutes = async () => {
const { payload } = await dispatch(getAsyncRouters() as any)
dispatch(addRoutes(payload))
}
const requestAuthInfo = async () => {
const {payload} = await dispatch(getAuthInfo() as any)
dispatch(addAuthInfo(payload))
}
if (getToken()) {
if (!routes.length) {
requestAsyncRoutes()
requestAuthInfo()
} else {
if (filePath !== "") {
if (hasMapFile(filePath)) {
return children
} else {
return <Navigate to='/404' />
}
}
return children
}
return children
} else {
return <Navigate to='/login' />
return <Navigate to='/login' replace={true} />
}
}