反应:this.props.location.pathname未定义

问题描述 投票:0回答:1

告诉我如何访问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>
        );      
    }
}
reactjs bootstrap-4 location react-router-dom pathname
1个回答
0
投票

您应该以这种方式在withRouter()中使用GeneralMenu HOC:

export default withRouter(GeneralMenu);

然后使用导出的元素。

您还可以执行类似的操作,而无需导出元素:

const WithRouterGeneralMenu = withRouter(GeneralMenu);
© www.soinside.com 2019 - 2024. All rights reserved.