将react-router-dom升级至5.x后,发现除去路由组件外的其他组件,无法直接获取history、location、match等相关属性。
一、组件该如何获取history等属性
路由组件 的获取方法
import React, {Component} from 'react'
class Father extends Component {
constructor(props) {
super(props)
}
render() {
return <App>
<Route path="/example" componnet="Example" />
</App>
}
...
}
export default Father
此时, Example 就是一个路由组件,可直接通过props直接获取history等属性。
其他组件 的获取方法
此处先假设:Foo 为 Example 的子组件, FooChild 为 Foo 的子组件。
针对Father、App、Foo、FooChild这些其他组件,获取方法通常涉及以下三种。
1、若组件为路由组件的子组件,可直接用props传值。
此方法一大弊处在于:若FooChild组件需要这些属性,而Foo组件并不需要这些属性,这种传值方式就显得很冗余,因为需要一层一层传值。
2、使用withRouter:专门用来处理数据更新问题。
当路由的属性值 history、location改变时,withRouter 都会重新渲染; withRouter携带组件的路由信息,可避免组件之间一级级传递。
import React, {Component} from 'react'
import {withRouter} from 'react-router-dom'
class FooChild extends Component {
constructor(props) {
super(props)
}
turn() {
this.props.history.push('/path')
}
...
}
export default withRouter(FooChild)
注意:
a. 确保withRouter在最外层;
b. 需要更新的组件需配合使用withRouter,否则即使FooChild执行了方法turn,页面仍然会停留在上一个页面的位置。 即:包含路由组件Example的父组件Father也需要配合使用withRouter
3、利用Context获取router对象
注意:此方法不建议使用,因为React不推荐使用Context
import React, {Component} from 'react'
// 必须
import PropTypes from 'prop-types'
class FooChild extends Component {
static contextTypes = {
router: PropTypes.object
}
constructor(props, context) {
super(props, context)
}
turn() {
this.context.router.history.push('/path')
}
...
}
export default FooChild
二、history的push和replace方法
push方法会将一个条目推到历史堆栈中,replace方法则 替换 历史堆栈中的当前条目。
在A页面中,利用Link进入B页面:
1、若在B页面通过push方法进入C,此时history.goBack(),可以返回到 B页面 ;
2、若在B页面通过replace方法进入C,此时history.goBack(),则返回到 A页面 。