安装react-router-dom
npm i react-router-dom
根目录新建Router.js
import Login from './views/login' import Layout from './views/layout' import { Component } from 'react' import { Route, BrowserRouter, Routes } from 'react-router-dom' class Router extends Component { render() { return ( <BrowserRouter> <Routes> // exact完全匹配路由 <Route exact path="/" element={<Layout/>} /> <Route exact path="/login" element={<Login/>} /> </Routes> </BrowserRouter> ) } } export default Router
index.js修改
import React from 'react'; import ReactDOM from 'react-dom/client'; import Router from './Router' const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <React.StrictMode> <Router/> </React.StrictMode> );
路由跳转
import {Link} from 'react-router-dom'; const App = () => { return( <div> <Link to="/loign">去登录</Link> </div> ) } export default App;
路径传参
// 注册路由 <Route exact path="/user/:uid" element={<user/>} /> // 路由跳转 <Link to="/user/10">个人中心</Link> // 接收参数 import { useParams } from 'react-router-dom'; const User = () => { const params = useParams(); return ( <div> { params.uid } </div> ) } export default User;
在6.X版本中接收参数需要使用useParams来接收,而useParams只能在函数组件使用;
而在类组件中使用this.props.match.params尝试,props打印出空对象!!!
问号传参
// 注册路由 <Route exact path="/user" element={<user/>} /> // 路由跳转 <Link to="/user?uid=10">个人中心</Link> // 接收参数 import { useLocation } from 'react-router-dom'; import qs from 'query-string'; const User = () => { let query = useLocation(); console.log(query); // {pathname: '/test/', search: '?uid=1', hash: '', state: null, key: 'default'} // 此时需要借助插件query-string将search转为对象 query = qs.parse(query.search); return ( <div> { query.uid } </div> ) } export default User;
state传参
// 注册路由 <Route exact path="/user" element={<user/>} /> // 路由跳转 <Link to="/user" state={{ uid: 10 }}>个人中心</Link> // 接收参数 import { useLocation } from 'react-router-dom'; const User = () => { let state= useLocation().state; return ( <div> { state && state.uid } </div> ) } export default User;
备注:state传参方式刷新后参数不会丢失;
但从URL上直接输入路由打开页面,state不存在;
使用时一定记得判断是否存在