React路由器获取主路由器组件上的当前位置 [英] React router get current location on main router component

查看:59
本文介绍了React路由器获取主路由器组件上的当前位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何从我用来定义路线的组件中获取当前位置.例如,我有一个名为 Routes 的组件,其中包含所有路由,如下所示:

I'd like to know how to get the current location from the component I've used to define my routes. For example, I have a component called Routes, which contains all the routes, like this:

class Routes extends React.Component {
    render() {
        return (
            <Router>
                <Nav />
                <header>{customHeader}</header>
                <Switch>
                    <Route exact path="/" component={Home} />
                    <Route path="/about" component={About} />
                    // Other routes
                </Switch>
            </Router>
        );
    }
};

但是,当我像在其他组件中那样尝试访问 this.props.location.pathname 时,它返回 undefined.

However, when I try to access this.props.location.pathname as I do in other components, it returns undefined.

在其他组件上,我需要使用 withRouter 以便能够访问 location 信息.但是我不能将它与 Routes 组件一起使用,因为它会抛出错误.

On the other components I need to use withRouter in order to be able to access the location information. But I can't use it with the Routes component, because it will throw an error.

我实际上并不需要pathname,我只想检查用户是什么路由,因为在访问特定页面时我会呈现不同的标题内容.

I don't actually need the pathname, I just want to check what route the user is, because I'll render a different header content when accessing a specific page.

推荐答案

将您的标题包装在始终呈现的 中.然后你就可以通过 props 访问所有东西.

Wrap your header in a <Route> that always renders. Then you'll have access to everything via props.

class Routes extends React.Component {
    render() {
        return (
            <Router>
                <Nav />
                <Route render={(props) => {
                  console.log(props.location)
                  return (
                    <header>{customHeader}</header>
                  )
                }} />

                <Switch>
                    <Route exact path="/" component={Home} />
                    <Route path="/about" component={About} />
                    // Other routes
                </Switch>
            </Router>
        );
    }
};

这篇关于React路由器获取主路由器组件上的当前位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆