(一)方案
BrowserRouter 换为 HashRouter文章来源地址https://www.toymoban.com/news/detail-639973.html
(二)代码
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)
)
文章来源:https://www.toymoban.com/news/detail-639973.html
到了这里,关于277/300 React+react-router-dom+Vite 二级页面刷新时,白屏问题解决的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!