withRouter 不会将 Route props 传递给组件

withRouter Does Not passes Route props to component

这是我的导航组件:

import React from 'react'

class Navigation extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      type: 'signUp', // or login
      showModal: false,
      isLoggedIn: false,
    }
  }

  ...some code

  render() {

    const { showModal, type, isLoggedIn } = this.state

    console.log(this.props.location); // all problem is this, I'm not getting it in console

    return(
      ...some more code
    )
  }
}

export default withRouter(Navigation)

这是它在 app.js

中使用的地方
class App extends React.Component {

  render () {
    return(
      <Router>
          <Fragment>

            <Navigation /> // <= right there

            <Switch>
              <Route exact path='/' component={HomePage}/>
              <Route exact path='/search' component={HomePage}/>
              <Route component={Lost} />
            </Switch>
          </Fragment>
      </Router>
    )
  }
}

我想在我的 <Navigation /> 组件中获取更新的路由道具,例如 matchlocation 以及 history 但是 我仅当该组件第一次安装在 DOM 上时才获取它,在我的其他组件中,我使用 window.history.pushState 更新了路由,但我无法在 link 之后从 withRouter 获取路由道具浏览器已更新。

我用 window.history.pushState 更新路线,因为:

  1. 我找不到任何方法来更新地址栏中的 link 而不显示用户或使用 React 路由器 DOM 将用户重定向到新组件(我在做吗方法对不对?)

  2. 基于此,我然后使用 window.location.pathname 为某些组件添加一些特定的样式)

另外,我通读了 and 但我无法解决这个问题。我做错了什么?

withRouter gives you the closest <Route>'s route props, and since the Navigation component is not inside a Route you will not get the route props.

你可以,例如将 Navigation 组件放在 Switch 之外的 Route 上,它将始终可见。

例子

class App extends React.Component {
  render() {
    return (
      <Router>
        <Fragment>
          <Route path="/" component={Navigation} />
          <Switch>
            <Route exact path="/" component={HomePage} />
            <Route exact path="/search" component={HomePage} />
            <Route component={Lost} />
          </Switch>
        </Fragment>
      </Router>
    );
  }
}