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

前端 未结 4 1197
野的像风
野的像风 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条回答
  •  南旧
    南旧 (楼主)
    2021-02-20 14:22

    After digging through their GitHub issues, I found the solution. I must render a within and pass the rest of my app into its render() function with history as a parameter. Within the render function, I can find the app's location in history.location.pathname.

    class App extends Component{
      render(){
        return (
          
    
            // We must add a parent  and render its children while passing 'history' as parameter
             
    
              // Within render(), we can find it in history.location.pathname
              
    ...
    }/> }} />
    ); } }

    This will update the history parameter automatically, without having to re-render on componentDidMount() or componentDidUpdate()

提交回复
热议问题