react-router @4用法整理
文章目录
router@4
这篇文章主要介绍了react-router@4的基本用法,包括动态路由,编程式导航等
- 安装
- switch用法
- 动态路由的基本用法
- 编程式导航(withRouter)
- 总结
-
安装
npm i react-router-dom -S - switch用法
示例代码:
import { Switch, BrowserRouter as Router, Route, Redirect} from 'react-router-dom';
class SwitchCom extends Component {
render() {
return (
<Router>
<Switch>
<Route path="/cart" component={Cart}></Route>
<Route path="/search" component={Search} />
<Route path="/home" component={Main} />
<Redirect from="/" to="/home"></Redirect>
<Route path="/mine" component={Mine}></Route>
<Route path="/class" component={Class}></Route>
<Route component={NoMatch}></Route>
</Switch>
</Router>
)
}
}
关于路由重定向: 使用
Redirect..from..to的格式,注意位置需要在定义to路由的后面,比如to="/home",重定向就需要写在Route path="/home"后面
关于404路由匹配,默认写在路由末尾,前面的路由都不匹配时,自动匹配404
关于Route,必须写在Router标签里面,否则会报错
3.动态路由的基本用法:
import { BrowserRouter as Router, Route, NavLink} from 'react-router-dom';
<div className="tab-bar">
<Route path="/index" exact component={Index}></Route>
<Route path="/index/news" component={News}></Route>
<Route path="/index/course" component={Course}></Route>
<Route path="/index/mine" component={Mine}></Route>
<ul className="footer">
<li><NavLink exact to="/index" activeStyle={{ color: '#4dc060' }}>首页列表项目 </NavLink></li>
<li><NavLink to="/index/news" activeStyle={{ color: '#4dc060' }}>资讯</NavLink></li>
<li><NavLink to="/index/course" activeStyle={{ color: '#4dc060' }}>课程</NavLink></li>
<li><NavLink to="/index/mine" activeClassName="selected">我的</NavLink></li>
</ul>
</div>
上面的
exact表示绝对匹配/index,如果不注明exact,则/index还会匹配/index/new等等
上面代码实现了一个类似tabbar切换的效果
关于NavLink 和 Link:
如果仅仅需要匹配路由,使用Link就可以了,而NavLink的不同在于可以给当前选中的路由添加样式, 比如上面写到的activeStyle和activeClassName
4.编程式导航(withRouter用法)
import {withRouter} from 'react-router-dom';
goBack(){
this.props.history.goBack();
}
goDetail(){
this.props.history.push('/detail');
}
goDetailWithParam(item){
this.props.history.push({pathname : '/cart',state:{item}});
}
<span className="ico" onClick={this.goBack.bind(this)}>
<i className="iconfont"></i>
</span>
//这里的item来自for循环的每一项
<li onClick={this.goDetailWithParam.bind(this,item)} key={encodeURI(item.imgUrl)}>
export default withRouter(Header);
引入
withRouter之后,就可以使用编程式导航进行点击跳转, 需要注意的是export default的暴露如上面所写,如果结合redux使用,则暴露方式为:withRouter(connect(...)(MyComponent))
调用history的goBack方法会返回上一历史记录
调用history的push方法会跳转到目标页,如上面goDetail方法
跳转传参:push()可以接收一个对象参数,跳转之后,通过this.props.location.state接收
5 总结:
刚做过一个React的项目,搭配路由选择了react-router @4 ,收获挺多的,打算写文章记录一下收获(也算是遇到的一些坑). 感觉@4比之前的router版本更加灵活一些,用法也更加简洁.还是挺好用的.官方文档也只是用到哪些就看一看,并没有从头看到尾,所以理解还不是很深刻,如果上面理解有偏差,还望指出,共同进步.
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论