1. withRouter的作用
withRouter是不通过路由跳转的组件,将history、locattion、math放在页面的props 对象中,
默认情况下,必须是经过路由匹配的组件才可以使用this.props,才会拥有路由的参数,一般首页,不是通过路由跳转过来的,而是直接从浏览器中输入地址打开的,如果不使用withRouter此组件的this.props为空,没法执行props中的history、location、match等方法
2. 应用
设置withRouter很简单只需要两步:
(1)引入
(2)将App组件 withRouter() 一下
import {Switch,Route,NavLink,Redirect,withRouter} from 'react-router-dom' //引入withRouter
const withRouterDemo=(props)=>{
//此时才能获取this.props,包含(history, match, location)三个对象
console.log(this.props); //输出{match: {…}, location: {…}, history: {…}, 等}
return (
<div>
<NavLink to='/one/users'>用户列表</NavLink>
<NavLink to='/one/companies'>公司列表</NavLink>
<Switch>
<Route path='/one/:type?' />
<Redirect from='/' to='/one' exact />
<Route component={NotFound} />
</Switch>
</div>
)
}
export default withRouter(withRouterDemo)