react-router withRouter

来源:互联网 发布:大掌门boss数据 编辑:程序博客网 时间:2024/06/05 18:28

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

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

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

 <Route exact path="/Home" component={Home}/>var Home = ( {history,location,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));
原创粉丝点击