0

I just noticed that in react router (v3.x) a component unmounts and remounts if a path param changes. Is this the expected behaviour?

Route:

<Route path="/landing/register/:step" component={Register}/>

Now, lets say I am on route "/landing/register/personal-data" and I am navigating via <Link/> or router.push({...}) to the next registration step "/landing/register/address", the Register-component gets first unmounted and then mounted again, loosing all its state.

Is this the correct way or am I doing something wrong?

EDIT:

It seems that the problem is that I am using nested routes, where I use a component for the parent route.

This example works (not re-mounting Register-Comp on path param change):

<Route path="/landing">
   <Route path="register/:step" component={Register}></Route>
</Route>

But when I use a component for the parent route, it doesnt (not re-mounting AppView-Comp, but Register-Comp on path param change):

<Route path="/landing" component={AppView}>
   <Route path="register/:step" component={Register}></Route>
</Route>
Felix Hagspiel
  • 2,634
  • 2
  • 30
  • 43
  • 1
    You might want to change [this answer](https://stackoverflow.com/questions/32261441/component-does-not-remount-when-route-parameters-change) to understand how component unmount/remount on URL params change – Rowland Sep 15 '17 at 08:45
  • I think this lead me to the correct path (see my edited question). The parent component `AppView` receives new props, and is triggering a re-render, leading to re-mounting the child components. I think I have to store the state elsewere, or do a check in `shouldComponentUpdate` – Felix Hagspiel Sep 15 '17 at 11:58

1 Answers1

0

I solve this problem by nesting routes in child components, like this:

// Router class
 <Route path="/landing/register" component={Register}/>


 //Register component

 <BrowserRouter>
  <div> 
   <Route path="/landing/register/personal-data" component={PersonalData}/>
   <Route path="/landing/register/payment-data" component={PaymentData}/>
   ...other routes
  </div>
 </BrowserRouter>

But in this case i store user data in redux store instead of component state, however you can store it on your component state it is not problem.

Artem Mirchenko
  • 2,140
  • 1
  • 9
  • 21