1. 下载插件
yarn add react-router-dom --save / npm i react-router-dom --save
2. 配置基础路由
import { BrowserRouter, Route, Link } from 'react-router-dom' <Provider> <BrowserRouter> <div> <ul> <li> <Link to="/">一营</Link> </li> <li> <Link to="/Erying">二营</Link> </li> <li> <Link to="/Qibing">骑兵连</Link> </li> </ul> // exact用来精准匹配路由 <Route path="/" exact component={App} /> <Route path="/Erying" component={Erying} /> <Route path="/Qibing" component={Qibing} /> </div> </BrowserRouter> </Provider>
3. 重导向(Redirect)
import { Redirect } from 'react-router-dom' <Redirect to="/somePath" ></Redirect> // 每次页面加载首先进这个地址
4. Switch匹配
import { Switch } from 'react-router-dom' <Switch> <Route path="/" exact component={App} /> <Route path="/Erying" component={Erying} /> <Route path="/Qibing" component={Qibing} /> <Route component={NoMatch} /> // 没有匹配到任何地址, 404的情况 </Switch>
5. 子路由嵌套
<Route path="/" render={() => <Admin> <Switch> <Route path="/home" component={ Home } /> <Route path="/ui/buttons" component={ Buttons }></Route> <Route path="/form/login" component={ FormLogin }></Route> <Route path="/charts/line" component={ ChartLine }></Route> <Route path="/permission" component={ PermissionIndex }></Route> <Redirect to="/home" /> <Route component={ NoMatch } /> </Switch> </Admin> }/>