React之withRouter的作用和应用

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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值