react-router v6 路由
前言
之前写react的时候 路由真的是难用,这次更新后,极为好用!
嵌套路由
main.jsx
import './index.css';
import * as React from 'react';
import './utils/leancloud-helper';
import * as ReactDOM from 'react-dom/client';
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
const Home = React.lazy(() => import('./pages/home'));
const Admin = React.lazy(() => import('./pages/admin'));
const AdminHome = React.lazy(() => import('./pages/admin/home'));
const User = React.lazy(() => import('./pages/admin/user'));
const Ban = React.lazy(() => import('./pages/admin/ban'));
const router = createBrowserRouter([
{
path: '/',
element: <Home />
},
{
path: 'admin',
element: <Admin />,
children:[
{
path: '',
element: <AdminHome />,
},
{
path: 'user',
element: <User />,
},
{
path: 'ban',
element: <Ban />,
}
]
}
]);
const rootEl = document.querySelector('#root');
ReactDOM.createRoot(rootEl).render(
// 如果路由开启了懒加载 这里一定要加 React.Suspense包裹
<React.Suspense>
<RouterProvider router={router} />
</React.Suspense>
);
嵌套路由的父路由组件需要这么写
admin/home/index.jsx
import { Outlet } from "react-router-dom";
// 声明式
const Admin = () => {
return <Outlet/>; // 相当于vue里的<router-view/>
};
export default Admin;
其它页面写法 就是正常写法即可。
跳转页面
import { useNavigate } from "react-router-dom";
// 组件中
const navigate = useNavigate();
navigate('/admin/user');