react-router路由懒加载/路由守卫

luyifo / 2024-03-09 / 原文

路由懒加载

目前在网络上搜到的路由懒加载方式基本都是通过React.lazy()方法配合Suspense的方式,可能是受vue-router的影响,我很不喜欢这种方式,不喜欢就改变。

上代码

import {createBrowserRouter} from "react-router-dom";

const router = createBrowserRouter([
    {
        path: "/",
        async lazy() {
            const {App} = await import("../App.jsx")
            return {Component: App}
        },
        children: [
            {
                path: "/news", async lazy() {
                    const {News} = await import("../pages/News.jsx")
                    return {Component: News}
                }
            },
            {
                path: "/about", async lazy() {
                    const {About} = await import("../pages/About.jsx")
                    return {Component: About}
                }
            },
        ]
    }
])

export default router

有几个注意点

  1. 组件导出方式不能使用默认导出,而使用分别导出的方式,在引入的时候用解构引入
  2. 这种路由懒加载方式不能在外层套自高阶组件,我暂时想不到怎么做,如果有人能解决希望分享出来
  3. 套高阶组件无非是想实现路由守卫的功能,下面提供另一种方式实现路由守卫的功能

路由守卫

用过Vue的都知道,Vue有官方自己的router,里面的路由守卫确实好用,而react只能自己实现.
路由守卫无非就是路由跳转的时候可以干点什么,现在网络上大都是封装高阶组件的方式实现,看看都觉得繁琐,,一顿花里胡哨不如下面几行,你细品

function App(){
	const navigate = useNavigate()
	const {pathname} = useLocation()
	const logged = isLogin()

	useEffect(() => {
		if (!logged && pathname !== "/auth") {
			navigate("/auth")
		}
	}, [pathname]);

	return <h1>hello world</h1>
}
export default App