美文网首页
react v6 路由

react v6 路由

作者: 汀上 | 来源:发表于2022-05-05 16:52 被阅读0次

    1.switch被废弃,使用routes替代
    2.嵌套路由使用< Outlet />
    3.跳转方式改变,新增hook useNavigate/useLocation/useRoutes等

    v6自动生成路由

    import React,{useState} from "react";
    import { BrowserRouter as Router, Routes, Route, Navigate } from "react-router-dom";
    
    import Home from "../pages/home";
    import Error from "../pages/404";
    const CollectRouter = ({ routes }) => {
      const [userInfo,setuserInfo] = useState(auth.getUser() || '');
      const initRoute = (routeArray) =>
        routeArray.map((v) => (
          <Route
            path={v.path}
            key={v.path}
              element={userInfo || v.path ==='/login'?<v.element />:<Navigate to='/login' replace />}
            children={v.children && initRoute(v.children)}
          />
         //注意这里的element以及children,值与5不同,嵌套路由方式升级
        )
      );
      return (
        <Router>
    //switch废弃,改用routes
          <Routes>
            <Route path="/" element={userInfo?<Home />:<Navigate to='/login' replace />} />
            {initRoute(routes)}
            <Route path="*" element={<Error />} />
          </Routes>
        </Router>
      );
    };
    
    export default CollectRouter;
    
    

    自动读取文件,并讲page下的文件自动生成路由树 (待优化)

    let context = require.context('../pages', true, /\.js$/);
    let paths = context.keys();
    let routes = paths.map(d => {
      return {
        path: d.substr(1).replace(/(\/index\.js|\.js)$/, ""),
        element: context(d).default,
      }
    })
    
    function getRouteTree(routes) {
      routes.forEach(el => {
        let _path = el.path.substr(1).split('/');
        if (_path.length <= 1) {
          el.id = _path.join('');
        } else {
          // el.path = _path.slice(-1)[0];
          el.id = _path.join('/');
          _path.pop();
          el.parent_id = _path.join('/');
        }
      });
      let tree = [];
      routes.forEach(el => {
        if (el.element.params) { el.path = el.path + el.element.params }
        if (el.parent_id) {
          let target = routes.find(v => v.id === el.parent_id);
          if (!target.children) {
            target.children = []
          }
          target.children.push(el)
        } else {
          tree.push(el)
        }
      })
      return tree
    }
    
    export default getRouteTree(routes)
    

    相关文章

      网友评论

          本文标题:react v6 路由

          本文链接:https://www.haomeiwen.com/subject/qicoyrtx.html