React-关于withRouter

react-router 提供了一个withRouter组件 

withRouter可以包装任何自定义组件,将react-router 的 history,location,match 三个对象传入.

无需一级级传递react-router 的属性,当需要用的router 属性的时候,将组件包一层withRouter,就可以拿到需要的路由信息.

如果是route直接的component的对象,是不需要加载withRouter的.如果只加载到其中的组件,则需要加上withRoute.

假如有个需求,是面包屑或者导航组件里需要拿到this.props.location(导航组件或者面包屑一般不会包裹在Route里吧),那么直接这么写显然就不行了。这个时候withRouter修饰一下,就可以这么写了。

正如下面代码所示,Route中的component中的IndexAsync是不需要加上withRoute,而IndexAsync中加载进来的组件,则是需要加载withRouter

        <Router>
                <div>
                    <Switch>
                        <Route exact path={PATH.DEFAULT} component={IndexAsync}/>
                        <Route path={PATH.HOME} component={IndexAsync}/>
                        <Route>
                            <Redirect to={PATH.DEFAULT}/>
                        </Route>
                    </Switch>
                </div>
        </Router>

如果我加载了一个PlaceHolder的组件,并且加载到IndexAsync中,则需要通过withRouter 来进行修饰,来获取props中的location和histrory对象

const mapStateToProps = state => {
    return {...state};
};

export default withRouter(connect(mapStateToProps)(Placeholder));

猜你喜欢

转载自blog.csdn.net/ci250454344/article/details/87279554