首页 > 解决方案 > 反应:this.props.location.pathname 未定义

问题描述

告诉我如何访问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>
        );      
    }
}

标签: reactjsbootstrap-4locationreact-router-dompathname

解决方案


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

export default withRouter(GeneralMenu);

然后使用导出的元素。

你也可以做这样的事情,而不导出元素:

const WithRouterGeneralMenu = withRouter(GeneralMenu);

推荐阅读