React V6路由配置:
1】安装路由
npm i react-router-dom --save #或者 yarn add react-router-dom --save
2】创建路由管理文件( router/index.js )
/* src/router/index.js */ import React from 'react'; //必须引入 import { BrowserRouter, Route, Routes } from 'react-router-dom' import { lazy, Suspense } from 'react' //路由懒加载 //Suspense必须使用这个 不然页面跳转时会报错 // BrowserRouter 地址无#,HashRouter为哈希路由地址带# const App = lazy(() => import('../App')); //页面 const HomeDiv = lazy(() => import('../home/index')); //二级页面 const WordDiv = lazy(() => import('../word/index')); //二级页面 const Router = () => { return ( <BrowserRouter> <Suspense> <Routes> <Route path='/' element={<App></App>}></Route> <Route path='/home/:id?' element={<HomeDiv></HomeDiv>}> {/* 级下多个路由同时显示 需要与父级路由地址一致 */} <Route path='/home/' element={<WordDiv></WordDiv>}></Route> <Route path='word/:id?' element={<WordDiv></WordDiv>}></Route> {/* 二级路由 注意地址前面没有斜杠 */} </Route> </Routes> </Suspense> </BrowserRouter> ) } export default Router
3】替换成路由入口文件( src/index.js )
/* src/index.js */ import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; // import App from './App'; //去掉 import reportWebVitals from './reportWebVitals'; import Router from './router/index.js' //引入路由管理文件 const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <React.StrictMode> <Router /> {/* 替换成 路由管理 */} </React.StrictMode> ); reportWebVitals();
4】设置路由显示
/* src/App.js */ import React from 'react'; import { useNavigate, Outlet } from 'react-router-dom' function App() { //路由跳转 const navigate = useNavigate();//必须在Routes组件下使用才有窗口上下文 const goto = (value) => { navigate(value); //navigate(value,{state:{id:'test'}); }; return ( <div className='bodys'> {/* 跳转路由 */} <div className='menus'> <div className='menus_C'> <div className='texts' onClick={() => goto('/')}>首页</div> <div className='texts' onClick={() => goto('/home')}>文档</div> <div className='texts' onClick={() => goto('/home/word')}>组件</div> </div> </div> <div className='box'> {/* Outlet 路由显示页面块 */} <Outlet /> </div> </div> ); } export default App;
5】其他路由属性
import {useNavite} from react-router-dom' const navite=useNavite() 斜杠形式传参 navite('/user/id='+'test') 问号形式传参 navite('/user?id=test') 隐式方式传参 这种形式路由中不会出现参数 navite('/user',{state:{id:'test'}) 获取斜杠传参的路由参数 import {useParams} from 'react-router-dom' const param=useParams() console.log(param.id) --> test 获取问号形式传参的参数 import {useState} from 'react' import {useSearchParams} from 'react-router-dom' const [searchParam,setSearchParam]=useSearchParams() consoloe.log(searchParam.get('id')) --> test 可以通过 setSearchParam({id:'新的属性值'}) 修改参数 获取隐式传值的路由参数 import {useLocation} from 'react-router-dom' const location=useLocation() consoloe.log(location) --->其中包含的有state中的参数值
547 Views