我想知道如何从我用来定义路线的组件获取当前位置。例如,我有一个名为 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
组件一起使用,因为它会抛出错误。
我实际上并不需要路径名
,我只是想检查用户是什么路线,因为访问特定页面时我会渲染不同的标题内容。
最佳答案
将标题包裹在 <Route>
中总是呈现。然后你就可以通过 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>
);
}
};
关于reactjs - React router 获取主路由器组件上的当前位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43404532/