v5版本例子代码
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom'
import App from '@/App'
import Home from '@/views/Home/Home'
import Fast from '@/views/Fast/Fast'
import User from '@/views/User/User'const BaseRouter = () => {return (<Router><Switch><Route path="/" component={()=>(<App><Switch><Route exact path="/home" component={Home}></Route><Route exact path="/fast" component={Fast}></Route><Route exact path="/user" component={User}></Route></Switch></App>)}></Route></Switch></Router>)
}
export default BaseRouter
今晚使用使用v6.1.1重写了下
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import App from "@/App";
import Home from "@/views/Home/Home";
import Fast from "@/views/Fast/Fast";
import User from "@/views/User/User";const BaseRouter = () => {return (<Router><Routes><Route path="/" element={<App />}><Route path="/home" element={<Home />}></Route><Route path="/fast" element={<Fast />}></Route><Route path="/user" element={<User />}></Route></Route></Routes></Router>);
};
export default BaseRouter;
做个总结,react-router-dom@6相比之前的版本存在以下一些变化(以上demo中涉及到的)
1.BrowserRouter保持不变;
2.Switch替换成了Routes;
3.Route中统一使用element属性,去掉原来的component和render;
4.子路由可以省略上级路由了,比如/page1/page1-1以往需要写完整的Path,而目前可以继承上级页面的路由了,甚至斜线都可以省略;
5.useNavigate取代useHistory,并且api也有相应的变化;
6.新增了Outlet,作用相当于{this.props.children}
。
从主观上看,react-router-dom@6新版本的命名更加容易理解,使用更为简洁了