加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

react-router withRouter

发布时间:2020-12-15 06:47:36 所属栏目:百科 来源:网络整理
导读:react-router 提供了一个withRouter组件 withRouter可以包装任何自定义组件,将react-router 的 history,location,match 三个对象传入。 无需一级级传递react-router 的属性,当需要用的router 属性的时候,将组件包一层withRouter,就可以拿到需要的路由信

react-router 提供了一个withRouter组件
withRouter可以包装任何自定义组件,将react-router 的 history,location,match 三个对象传入。
无需一级级传递react-router 的属性,当需要用的router 属性的时候,将组件包一层withRouter,就可以拿到需要的路由信息

import {withRouter} from 'react-router-dom' ;
var  Test   = withRouter(({history,match})=>{ return <div>{location.pathname}</div> }) 

正常情况下 只有Router 的component组件能够自动带有三个属性 如下的Home 组件有

<Route exact path="/Home" component={Home}/>
var Home = ( {history,match})=>   <div>{location.pathname}</div>

如果使用了react-router-redux,则可以直接从state 中的router属性中获取location。不需要再使用withRouter 获取路由信息了

export default connect(({router}) => { return {pathname: router.location.pathname} })(MyControl) 

react-router-redux配置

const store = createStore( combineReducers({ ...reducer,router: routerReducer }),applyMiddleware(routeMiddleware)); 

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读