方法一:
路由的history对象:(前提是只对路由管理着的页面有效)
我们直接在页面中打印this.props,
export default class City extends React.Component{
render(){
console.log(this.props)
return(
<div>
<CityHeader title="城市选择" history={ this.props.history}/>
</div>
)
}
}
如下图,可以看到push和replace方法;
方法二:
window的history对象:
export default class Header extends React.Component {
backHandler = () =>{
window.history.back(); // 返回
}
PS:①this.props.history.push("/")----记录每次的效果,点击回到进来的页面;
②this.props.history.replace("/")----替换掉历史的效果;每次点击不能退回进来的页面;
③window.history.back();--- 和push一样点击回到进来的页面;
方法三:
路由自带的withRouter组件;引入之后就能从属性中获取history方法:
① 页面引入:
import { withRouter} from 'react-router-dom'
②export default导出:
export default withRout (导出的文件名)
使用withRouter方法的优点:
能够直接获取路由中的属性(比如:history);
需要传参的时候能直接将react-router的history、location、match三个对象传入props对象上,接收的时候this.props就能直接获取参数;
使用withRouter,获取到history方法,就能直接跳转到指定页面;