作用1. 使用Route包裹组件, 将react-router的history, location, match信息通过props传递给包裹的组件
默认情况下必须是经过路由匹配渲染的组件才存在this.props,才拥有路由参数,才能使用 函数跳转 的写法,执行
this.props.history.push('/***')
跳转到对应路由的页面。
然而不是所有组件都直接与路由相连(通过路由跳转到此组件)的,当这些组件需要路由参数时,使用withRouter
就可以给此组件传入路由参数,此时就可以使用this.props
。
import React from 'react'
import { withRouter } from 'react-router-dom'
export default withRouter((props) => {
const { history, location, match } = props
return <div>{location.pathname}</div>
})
作用2. 当前页面需要可以跳转到其他页面,比如使用 react-router-dom
NavLink
组件,这时候可以使用 withRouter
包裹组件。
import React from 'react'
import { withRouter, NavLink } from 'eact-router-dom'
export default withRouter((props) => {
return <div>
<span>测试</span>
<div><NavLink to="/" exact>首页</NavLink></div>
</div>
})