react 项目模板搭建(2)—— 加入 react-router-dom v6 路由

一、安装路由
npm install react-router-dom@6

结构目录
react 项目模板搭建(2)—— 加入 react-router-dom v6 路由_第1张图片

App.tsx

import React from 'react';
import { BrowserRouter } from 'react-router-dom'
// import logo from './logo.svg';
import './App.css';
import Layout from './layout'

function App() {
  return (
    <div className="App">
      <BrowserRouter>
        <React.Suspense fallback={<>正在加载……</>}>
          <Layout />
        </React.Suspense>
      </BrowserRouter>
    </div>
  );
}

export default App;

router / index.tsx
路由组件遍历渲染

import { Route } from 'react-router-dom'
import { routes, IRoute } from './routes'


export const RouteData = (data: any[]) => {
    return data.map((item: IRoute, index: number) => {
        return (
            <Route 
            	key={item?.key ? item?.key : index} 
            	path={item?.path} 
            	element={item?.element} 
            	caseSensitive={item?.caseSensitive}
            >
            {/* {item?.children ? RouteData(item?.children) : null} */}
                {item?.children && item?.children?.map((child: any) => {
                    return <Route
                        key={child?.key ? item?.key : item?.path}
                        path={child?.path}
                        element={child?.element}
                        caseSensitive={item?.caseSensitive}
                    />
                })}
            </Route>
        )
    })
}

export const routeRender = RouteData(routes)

router / routes.tsx
路由接口与路由数据

import React from 'react'
const Home = React.lazy(() => import('src/pages/home'))
const Childrenpages = React.lazy(() => import('src/pages/childrenpages'))
const Graph = React.lazy(() => import('src/pages/graph'))

export interface IRoute {
    caseSensitive?: boolean;
    children?: Array<IRoute>
    element?: React.ReactNode | null;
    index?: false;
    path: string;
    key?: any;
    title?: string;
    [name: string]: any;
}

export const routes: Array<IRoute> = [
    {
        path: '/',
        element: <Home />,
        children: [
            {
                path: 'childrenpages',
                element: <Childrenpages />
            }
        ]
    },
    {
        path: 'graph',
        element: <Graph />,
    },
    {
        path: 'childrenpages321',
        element: <Childrenpages />,
    }
]

layout / index.tsx
在布局文件中引入路由

import React from 'react';
import { Routes, Outlet } from 'react-router-dom'
import { routeRender } from '../router'
// import { routes } from '../router/routes'

class Layout extends React.Component {
    render(): React.ReactNode {
        console.log(routeRender);
        return (
            <div id='layout'>
                <Routes>
                    {/* {RouteData(routes)} */}
                    {routeRender}
                </Routes>
                <Outlet />
            </div>
        )
    }
}

export default Layout

使用路由的文件

home / index.tsx

import React from 'react'
import { useNavigate, Outlet } from 'react-router-dom'



const Home: React.FC = (props) => {
    const navigate = useNavigate();
    const gorouter = () => {
        navigate(`/graph?id=${id}`, {state: {id: 'ide', name: '名字', list: [{cid: '123'}]}})
    }

    return (
        <div id='home' onClick={gorouter}>123 <Outlet /></div>
    )
}

export default Home

这里出现了路由嵌套,按照react-router-dom的介绍,需要在父级使用为子路由占位,才会在跳转子路由时渲染
使用useNavigate做路由跳转,使用绝对路由进行跳转,相对路由会进行url拼接跳转

import React from 'react'
import { useNavigate, useParams, useSearchParams,useLocation } from 'react-router-dom'

const Graph: React.FC = (props) => {
    let param = useParams()
    console.log('useParams',param);
    const [searchParams, setSearchParams] = useSearchParams();
    console.log('useSearchParams', searchParams);
    console.log('useSearchParams', searchParams.get('id'));  // 获取url中的参数
    console.log('useLocation', useLocation());  // 获取路由对象中的参数
    const navigate = useNavigate();
    const gorouter = () => {
        navigate('/home/childrenpages',{replace: true})  // replace 重定向
    }
    return(
        <div onClick={gorouter}>Graph</div>
    )
}

export default Graph

useLocation() 获取的路由值

console.log('useLocation', useLocation());
{
	hash: "",
	key: "vtpp9hg6",
	pathname: "/graph",
	search: "?id=ide",
	state: {
		id: "ide"
		list: [
			{cid: "123"}
			],
		name: "名字",
	}
}

后续再详细更新……

参考:
React-Router v6 新版本路由封装
react-router-dom v6 使用
React-Router v6 新特性解读及迁移指南
react-router-dom v6 版本使用内容详解
react-router-dom V6 路由传值及功能介绍

你可能感兴趣的:(前端框架初步搭建,react.js,typescript,前端)