我想知道如何从我用来定义路线的组件中获取当前位置。例如,我有一个名为 Routes 的组件,其中包含所有路由,如下所示:
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.
在我需要使用的其他组件上withRouter,以便能够访问location信息。但是我不能将它与Routes组件一起使用,因为它会抛出错误。
我实际上并不需要pathname,我只想检查用户是什么路由,因为在访问特定页面时我会呈现不同的标题内容。