react-Router-dom的使用

react-Router-dom的使用

1. react-router提供了一个wthRouter组件javascript

特色:
1. withRouter能够包裹任何自定义组件
2. 将react-router的history、location、match三个对象传入

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">&#xe501;</i>
</span>
//这里的item来自for循环的每一项
<li onClick={this.goDetailWithParam.bind(this,item)} key={encodeURI(item.imgUrl)}>

export default withRouter(Header);

引入withRouter以后,就可使用编程式导航进行点击跳转

若是结合redux使用,则暴露方式为: withRouter(connect(...)(MyComponent))

调用history的goBack方法会返回上一历史记录

调用history的push方法会跳转到目标页,如上面goDetail方法

跳转传参: push()能够接收一个对象参数,跳转以后,经过this.props.location.state接收

2. 关于路由重定向java

使用Redirect..from ..to的格式

须要注意定义 to路由的后面好比 to="/home",

重定向就须要写在 Route path="/home"的后面

3. 404路由的匹配react

默认写在路由的末尾,当前面的路由都不匹配时,自动匹配404路由

4. route组件的使用编程

必须写在Router别名的HashRouter组件或者BrowserRouter组件

5. 关于NavLink和Link的用法redux

若是单纯的实现跳转就用 link

须要添加样式的那么就用 NavLink  (在于能够给当前选中的路由添加样式)
相关文章
相关标签/搜索