react-router-dom: getting props.location from within component

前端 未结 4 1266
野的像风
野的像风 2021-02-20 14:03

I have a simple App that uses BrowserRouter from \'react-router-dom\' v4. I\'m trying to access the location.pathname property from within the &l

4条回答
  •  Happy的楠姐
    2021-02-20 14:38

    You achieve what u have asked for by doing this

    import AccessRoute from './AccessRoute'
    
    class App extends Component{
      render(){
        return (
          
    
          
     
    ...
    ); } }

    AccessRoute.jsx

    import React from 'react'
    import {withRouter} from 'react-router';
    class AccessRoute extends React.Component{
        constructor(props){
            super(props);
        }
    
    
    
     //If you want to find the location on mount use this 
    
     componentDidMount(){
            console.log("the path name is ",this.props.location.pathname);
        }
    
    
     //If you want to find the location on change use this
    
      componentDidUpdate(prevprops){
        if(this.props.location.pathname!=prevprops.location.pathname){
            console.log("the new path name is ",this.props.location.pathname);
        }
    
    }
    
        render(){
            return(
    
                this.props.children
    
                );
        }
    }
    export default withRouter(AccessRoute)
    

提交回复
热议问题