vite4加react18加ts-路由篇

vite4加react18加ts-安装篇; 最近从vue3转型学习了,react相关技术架构,去有意识的去学习了相关东西,内容比较实用,没有引入太多原理和概念,就是最直接最实用的记录下来;

安装reat-router-dom
npm install reat-router-dom
项目中版本
"react-router-dom": "^6.6.1"
引入
/* main.tsx */
// BrowserRouter(history模式) HashRouter(hash模式)
import { BrowserRouter, HashRouter } from "react-router-dom";
import Router from '@/router/index';
ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
    <BrowserRouter>
    	<Router></Router>
    </BrowserRouter>
);
/* App.tsx */
/* 如果想所有的路由都被app这个组件包裹的话 */
import Router from '@/router/index';
/*题外: antd配置主题 */
import { ConfigProvider } from 'antd';
export default function App() {
	reutrn (
  	<div className="app">
    		/* 如果使用antd配置主题色的话 */
    		<ConfigProvider theme={{ token: { colorPrimary: '#387db5'}}>
        	<Router></Router>
        </ConfigProvider>
    </div>
  )
}
简单使用
// 1.创建路由表src/router/routers
import { lazy } from 'react';
const Routers = useRoutes([
	{path: 'login', component: lazy(() => import('@/views/Login/index'))},
  {path: 'home', component: lazy(() => import('@/views/Home/index')),
  	// 如果有子路由
    children: [
    	{path: 'shop', component: lazy(() => import('@/views/Home/Shop/index'))},
      {path: 'productDetails', component: lazy(() => import('@/views/ProductDetails/index'))},
    ]
  },
  {path: '/', redirect: 'login'}
]);
export default Routers;
// 2.遍历组装路由组装路由
import { Navigate, useRoutes } from "react-router-dom";
import { Suspense } from 'react'
import routes from "./routers";
// 遍历路由
const renderRoutes = (routes: any) => {
  return routes.map((item: any) => {
    const route:any = { meta: item.meta, path: item.path}
    if (item.children) { // 如果又子路由
      route.children = renderRoutes(item.children);
    };
    if (item.component) {
    	// Suspense来处理异步加载资源时页面应该如何显示的问题
      route.element = <Suspense><item.component /></Suspense>
    }
    if (item.redirect) {
      route.element = <Navigate to={item.redirect} />
    }
    return route
  })
}
// 导出路由
export default function Router () {
  console.log(renderRoutes(routes));
  return useRoutes(renderRoutes(routes));
}
// 3.main.tsx中使用
ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
    <BrowserRouter>
    	<Router></Router>
    </BrowserRouter>
);

嵌套子路由使用Outlet占位
import { NavLink, Outlet } from 'react-router-dom';
export default function Home () {
	return(
  	<div>
    	{/* 左侧布局 */}
      <ul>
      	{/* 子路由路径可以不加'/' */}
      	<li><NavLink to="message">消息</NavLink></li>
        <li><NavLink to="contacts">联系人</NavLink></li>
      </ul>
      {/* 右侧布局 */}
      {/*路由占位符-最终子路由将呈现再这里*/}
      <Outlet />
    </div>
  )
}
传参总结
  • state传参:BrowserRouter(history)模式下,刷新页面不消失;而HashRouter(hash)模式下,刷新页面会消失,但都不会暴露在url中
  • params传参(动态路由):可读性高,便于维护,当另一个页面一定需要某数据时,推荐使用
  • search传参:会暴露在url中,刷新页面不会消失,但取数据时,需处理
params
1.link组件to
<NavLink to=`home/${item.id}/${item.name}`/>
2.路由表
{path:'home/:id/:name', element<Home />}
3.组件内部使用useParams
import {useParams} from 'react-router-dom';
const {id,name,message} = useParams()
search传参
1.link组件to
<NavLink to=`home/?id=${item.id}&name=${item.name}`/>
2.组件内部使用useSearchParams
import {useSearchParams} from 'react-router-dom'
const [search, setSearch] = useSearchParams()
const id = search.get('id')
const name = search.get('name')
state传参
1.link state
<NavLink to=`home` state={{id: item.id, name: item.name}}/>
2.组件内部使用useLocation解析
import {useLocation} from 'react-router-dom'
const {state: {id, name}} = useLocation();
编程式路由导航
import {useNavigate} from 'react-router-dom';
const navigate = useNavigate();
// 
navigate(home, {
	replace: true;
  state: {id: id, name: name}
});

你可能感兴趣的:(javascript,react.js,typescript)