反应:this.props.location.pathname未定义 [英] React: this.props.location.pathname is undefined

查看:340
本文介绍了反应:this.props.location.pathname未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

告诉我如何访问路径名?参数 this.props 为空,并且 this.props.location 未定义.

Tell me how to access pathname? Parameter this.props is empty and this.props.location is undefined.

如何自动获取此参数而无需自行设置?

How to automatically get this parameter without having to set it yourself?

找到的大多数解决方案都需要我自己(手动)设置此参数,这不是很方便,而且会使代码复杂化.

Most of the solutions found require me to set this parameter myself (manually), which is not very convenient and complicates the code.

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>
        );      
    }
}

推荐答案

您应通过以下方式在 GeneralMenu 中使用 withRouter() HOC:

You should use the withRouter() HOC in your GeneralMenu in this way:

export default withRouter(GeneralMenu);

,然后使用导出的元素.

and then use the exported element.

您也可以执行以下操作,而无需导出元素:

You can also do something like this, without export the element:

const WithRouterGeneralMenu = withRouter(GeneralMenu);

这篇关于反应:this.props.location.pathname未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆