How to get current route in react-router 2.0.0-rc5

后端 未结 9 1273
无人及你
无人及你 2020-12-08 18:05

I have a router like below:


    
        
          


        
相关标签:
9条回答
  • 2020-12-08 18:34

    If you use the history,then Router put everything into the location from the history,such as:

    this.props.location.pathname;
    this.props.location.query;
    

    get it?

    0 讨论(0)
  • 2020-12-08 18:37

    After reading some more document, I found the solution:

    https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/location.md

    I just need to access the injected property location of the instance of the component like:

    var currentLocation = this.props.location.pathname
    
    0 讨论(0)
  • 2020-12-08 18:37

    Works for me in the same way:

    ...
    <MyComponent {...this.props}>
      <Route path="path1" name="pname1" component="FirstPath">
      ...
    </MyComponent>
    ...
    

    And then, I can access "this.props.location.pathname" in the MyComponent function.

    I forgot that it was I am...))) Following link describes more for make navigation bar etc.: react router this.props.location

    0 讨论(0)
  • 2020-12-08 18:38

    For any users having the same issue in 2017, I solved it the following way:

    NavBar.contextTypes = {
        router: React.PropTypes.object,
        location: React.PropTypes.object
    }
    

    and use it like this:

    componentDidMount () {
        console.log(this.context.location.pathname);
    }
    
    0 讨论(0)
  • 2020-12-08 18:41

    As of version 3.0.0, you can get the current route by calling:

    this.context.router.location.pathname

    Sample code is below:

    var NavLink = React.createClass({
        contextTypes: {
            router: React.PropTypes.object
        },
    
        render() {   
            return (
                <Link {...this.props}></Link>
            );
        }
    });
    
    0 讨论(0)
  • 2020-12-08 18:43

    Try grabbing the path using: document.location.pathname

    In Javascript you can the current URL in parts. Check out: https://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/

    0 讨论(0)
提交回复
热议问题