告诉我如何访问pathname
?参数this.props
为空,并且this.props.location
未定义。
如何自动获取该参数,而无需自行设置?
找到的大多数解决方案都需要我自己设置这个参数(手动),这不是很方便,而且代码很复杂。
ReactDOM.render(
<BrowserRouter>
<React.StrictMode>
<App />
</React.StrictMode>
</BrowserRouter>
document.getElementById('root')
);
function App() {
return (
<Container>
<Row><GeneralMenu /></Row>
<Row>
<Switch>
<Route exact path="/block1">
<PageStrategy />
</Route>
<Route exact path="/block2">
<PageStrategy />
</Route>
</Switch>
</Row>
</Container>
);
}
class GeneralMenu extends Component {
render() {
// {location} = this.props.location.pathname;
return (
<Navbar>
<Nav activeKey = {this.props.location.pathname}>
<Nav.Link href = "/block1">Block1</Nav.Link>
<Nav.Link href = "/block2">Block2</Nav.Link>
</Nav>
</Navbar>
);
}
}
发布于 2020-06-05 20:58:41
您应该以如下方式在您的GeneralMenu
中使用withRouter()
HOC:
export default withRouter(GeneralMenu);
然后使用导出的图元。
您也可以在不导出元素的情况下执行以下操作:
const WithRouterGeneralMenu = withRouter(GeneralMenu);
发布于 2020-06-05 21:26:29
<Nav activeKey = {window.location.pathname}>
此选项有效!
和
<Nav.Link as = {Link} to = "/block1">
相反,
<Nav.Link href = "/block1">
对于站点速度
https://stackoverflow.com/questions/62215266
复制相似问题