277/300 React+react-router-dom+Vite 二级页面刷新时,白屏问题解决

(一)方案

BrowserRouter 换为 HashRouter

(二)代码

import routes from './routes'
import  {ReactElement, Suspense} from 'react'
import {createHashRouter, Navigate} from 'react-router-dom'
// 生成路由数据
const generateRoutes = (routes:  Routes) => {
    return routes.map((item: RouteParams) => {
        const {component: Component} = item;
        const route: RouteObject = {path: item.path}

        if (item.redirect) {
            route.element = <Navigate to={item.redirect} replace/>
        } else if (Component) {
            route.element = <BeforeEach meta={item.meta} path={item.path}>
                <Suspense>
                    <Component/>
                </Suspense>
            </BeforeEach>
        }

        if (item.children) {
            route.children = generateRoutes(item.children)
        }

        return route
    })
}
export default createHashRouter(
    generateRoutes(routes)
)

(三)更多代码

import routes from './routes'
import  {ReactElement, Suspense} from 'react'
import {createHashRouter, Navigate} from 'react-router-dom'
// 生成路由数据
const generateRoutes = (routes:  Routes) => {
    return routes.map((item: RouteParams) => {
        const {component: Component} = item;
        const route: RouteObject = {path: item.path}

        if (item.redirect) {
            route.element = <Navigate to={item.redirect} replace/>
        } else if (Component) {
            route.element = <BeforeEach meta={item.meta} path={item.path}>
                <Suspense>
                    <Component/>
                </Suspense>
            </BeforeEach>
        }

        if (item.children) {
            route.children = generateRoutes(item.children)
        }

        return route
    })
}

// 路由拦截器
const BeforeEach = (props: { meta?: RouteMeta, children: ReactElement, path: String; }) => {
    const { userStore } = useStores()

    const { meta, children, path } = props

    // 未登录
    if(meta){
        if(meta.isAuth && !userStore.isLogin || meta.userStatus && meta.userStatus !== userStore.info.status){
            return (
                <AutoReverse path={path} />
            )
        }
    }

    // 设置标题
    if (meta?.title) {
        document.title = meta.title
    }

    document.body.style.backgroundColor = meta?.backgroundColor || '';

    return children
}

export default createHashRouter(
    generateRoutes(routes)
)

你可能感兴趣的:(react.js,javascript,前端)