How to pass the React Router location prop to a co

2019-07-13 09:07发布

问题:

I'm trying to figure out how to pass React Router's location prop to a component.

I have a route defined like so:

<Route
  path="placeholder"
  render={(props) => <Navigation {...props} />}
/>

In my Navigation component I do console.log(this.props); in the render method only to get an empty object. What gives? Isn't the location prop supposed to be automatically supplied to any component inside a Route?

By the way, I'm using react-router-dom version 4.2.2.

回答1:

You need to warp your component with withRouter in order to inject match, history and location in your component props.

import { withRouter } from 'react-router-dom';
class Navigation extends React.Component {

  render() {
    const { match, location, history } = this.props
    return (
      <div>{location.pathname}</div>
    )
  }
}

export default withRouter(Navigation)


回答2:

You need to use the withRouter function from 'react-router-dom' on you main component where you setup Routes wrapped in a Switch and you should have access to location prop on Navigation Component by using this.props.location

App.js


Class App extends Component {
  render(){
    return (
        <Aux>
            <Switch>
                <Route path="/login" exact component={Login}/>
                <Route path="/Navigation" component={Navigation}/>
                <Redirect to="/login"/>
            </Switch>
        </Aux>
    );
  }
}
export default withRouter(App);