React路由器获取主路由器组件上的当前位置
问题描述:
我想知道如何从我用于定义路由的组件获取当前位置。例如,我有一个叫做路由组件,它包含了所有的路径,像这样:React路由器获取主路由器组件上的当前位置
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
,我只是想检查用户是什么路由,因为在访问特定页面时我会呈现不同的页眉内容。
答
将您的标题包裹在始终呈现的<Route>
中。然后你可以通过道具获得所有的东西。
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>
);
}
};
一个解决方案是执行'location.pathname',它与react-router无关,但是来自浏览器。 –
@SaugatAcharya是的..这或验证到另一个组件将是我的其他选项。我只是想检查主要组件是否可行。 – celsomtrindade
你在'this.props.location'中得到了什么吗? –