React-router: Not unmounting and remounting Route Component as expected

Created on 23 Nov 2015  路  6Comments  路  Source: ReactTraining/react-router

I'm using gieger for flux, and react-router 1.0 within its context.

My initial render call renders the following:

<Context
  fooStore={fooStore}
  fooActions={fooActions}
  render={() => (
    <Router history={history}> // from createBrowserHistory() 
      <Route path="/" component={Master}> // a template component
        <IndexRoute component={HomePage} /> 
        <Route path=":userName" component={UserProfile}/>
        <Route path="*" component={NotFound}/>
      </Route>
    </Router>
  )} />

To navigate to a route I am accessing the RR history object through React context:

_someCallBack = () => {
    this.context.history.pushState(null, `/${userName}`); // userName is an alphanumeric string
}

When the call to pushState occurs from within the HomePage component, this works as expected, navigating to /userName and rendering the UserProfile component.

However, if I call pushState while on the :userName route, it will change the URL correctly, but it will not unmount and re-mount the UserProfile component with the correct props.params object.

Does RR think that I am trying to navigate to the same route, and therefore not do anything?

Seems like a bug, but it is possible I am doing something wrong.

Most helpful comment

Link is now https://github.com/reactjs/react-router/blob/master/docs/guides/ComponentLifecycle.md

[edit] this is out of date and this link doesn't work either (as you can probably tell by the number of :-1:s)

All 6 comments

Alas I was doing it wrong. React router does not unmount the component, but it does pass the new props. These can be captured using componentWillReceiveProps(nextProps).

Thanks, this helped solve my problem too! Request for this to be added to the documentation?

Link is now https://github.com/reactjs/react-router/blob/master/docs/guides/ComponentLifecycle.md

[edit] this is out of date and this link doesn't work either (as you can probably tell by the number of :-1:s)

@DerFlatulator I found a fix for this bug, see https://github.com/ReactTraining/react-router/issues/1982#issuecomment-275346314

If for some reason you want to remount every time, you can force it using the key parameter on the Route.render.
Example:

<Route 
    path=":userName" 
    render={props => 
        <UserProfile 
            key={props.match.params.userName}/>} 
            userName={props.match.params.userName}/>
    } />

I'm not quite sure of the syntax but you get the idea.

Was this page helpful?
0 / 5 - 0 ratings