【问题标题】:React: this.props.location.pathname is undefined反应:this.props.location.pathname 未定义
【发布时间】:2020-06-05 12:21:33
【问题描述】:

告诉我如何访问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】:

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

export default withRouter(GeneralMenu);

然后使用导出的元素。

你也可以这样做,不导出元素:

const WithRouterGeneralMenu = withRouter(GeneralMenu);

【讨论】:

    【解决方案2】:
    <Nav activeKey = {window.location.pathname}>
    

    此选项有效!

    <Nav.Link as = {Link} to = "/block1">
    

    改为

    <Nav.Link href = "/block1">
    

    网站速度

    【讨论】:

      猜你喜欢
      • 2014-09-18
      • 2018-07-06
      • 1970-01-01
      • 2021-09-20
      • 2018-05-20
      • 2019-04-27
      • 2017-12-21
      • 1970-01-01
      • 2023-03-31
      相关资源
      最近更新 更多