一、路由跳转与传值
路由控制跳转的组件中(一般是views目录下的页面组件),props会自动添加以下三个字段, (根组件和components中的组件没有路由信息)
history : 主要用于路由跳转和路由监听
location: 主要显示路由信息, 可用于路由传值
match: 主要用于路由传值, 也可展示路由信息
react路由跳转方式1: 路由标签Link跳转
<Link to="/user">跳转个人中心</Link> <br/>
react路由跳转方式2: 编程式导航跳转
<button onClick={()=>{
props.history.push('/user')
}}>跳转个人中心</button>
react路由传值方式1: url路径拼接传值
<Link to={"/user?name="+name}>url路经拼接传值</Link>
接收 {decodeURI(this.props.location.search)}
react路由传值方式2: 动态路由(友好url)传值
<Link to={"/user/"+name}>动态路由(友好url)传值</Link>
接收 {this.props.match.params.name}
react路由传值方式3: 自定义对象传值
<Link to={{
pathname: "/user",
data: { name }
}}>自定义对象传值</Link>
接收 {this.props.location.data && this.props.location.data.name}
二、路由监听
(一): 局部路由监听:
1, 在路由跳转的组件中使用props.history.listen() 监听路由, 得到返回值cancle
this.cancle = props.history.listen((route, type)=>{})
2, 在组件的componentWillUnmount中取消路由监听, 调用 cancle函数, 以防止重复监听,浪费性能
this.cancle()
注: 局部监听只能监听此组件离开时的路由, 类似于vue中beforeRouteLeave() 路由守卫
(二): 全局路由监听:
1, 在app.js中从路由模块导入withRouter
import { withRouter } from 'react-router-dom'
2, 导出App时,用withRouter 函数处理后导出, 把路由数据添加到props中
export default withRouter(App);
3, 在app根组件的componentDidMount函数中添加全局路由监听
componentDidMount() {
console.log(this.props)
this.props.history.listen(path=>{
console.log("全局路由监听" + path.pathname)
})
}
注: 全局路由监听,根组件App中没有路由信息, 需要使用高阶组件withRouter添加路由信息,然后监听