React-router
介绍:
1、路由是根据不同的url地址展示不同的页面或者内容
2、安装:npm install react-router-dom@5
使用:
导入
import {HashRouter, Route} from 'react-router-dom'
定义路由
render() {
return (
<div>
<HashRouter>
<Route path="/home" component={Home} />
<Route path="/second" component={Second} />
<Route path="/mine" component={Mine} />
</HashRouter>
</div>
)
}
(1)建议:将路由单独封装在一个 js 文件中
(2)注意一级路由与多级路由
重定向
含义:如果我们不想让用户访问某个路由或者该路由不在我们书写的路由中,我们可以让组件跳转到我们指定的路由。
//模糊匹配,重定向
<Redirect from="/" to="/home" exact />
//exact 精确地
<Route path="*" component={Text} />
嵌套路由
父组件:
<Route path="/home" component={Home} />
子组件:
<Route path="/home/page1" component={Page1} />
<Route path="/home/page2" component={Page2} />
<Redirect from="/home" to="/home/page1" />
路由跳转
(1)声明式路由
<NavLink to="/home" activeClassName="ok">home</NavLink>
<NavLink to="/second" activeClassName="ok">second</NavLink>
<NavLink to="/mine" activeClassName="ok">mine</NavLink>
(2)编程式路由
- this.props.history.push(路由)
- props.history.push(路由)
-
import {useHistory} from 'react-router-dom' const history = useHistory() history.push(路由)
路由传参
(1)
<Route path='/detail/:id' component={Detail} />
动态路由,:代表动态,id 可以替换,在 props.match.params 中可以获取;
(2)
history.push({
pathname:'/detail',
query:{id}
})
props.location.query.id
(3)
history.push({
pathname:'/detail',
state:{id}
})
props.location.state.id
路由拦截
<Route path='/test' render={() => {
判断 ? <Home/> : <Login/>
}} />
路由模式
- HashRouter
- BrowserRouter