Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ComponentDidMount fires twice

I have an issue with navigating between two routes. My scenario is as following:

I have 2 routes: Route1 and Route2 - both being siblings to each other.

Let say I am at the Route1, from which I can navigate to Route2 with parameters passed (always). I have investigated buggy behaviour when quickly navigating in the following manner:

Route1 -> Route2 (param: 1) -> Route 1 -> Route 2 (param: 2)

I've placed console logs in the Route2 componentDidMount to see what is the output of the following:

const { navigation } = this.props;
console.log(navigation.state.params.param);

To my surprise, if I navigate quickly, the output for the scenario above will be:

1 
1 
2

While the expected behaviour is:

1
2

Any idea whats going on?

like image 207
uksz Avatar asked Nov 30 '25 13:11

uksz


2 Answers

When you navigate from Route2 to Route1, does it come in from the right or left? It's probably getting mounted twice because react-navigation is fun that way :P

You might also be pressing the button too fast. In that case, disable the button for a few hundred ms after the first click.

class Button extends React.Component {
  onPress = () => {
    if (this.props.disabled) return;
    if (this.canPress) {
      this.canPress = false;
      this.props.onPress();
      setTimeout(() => { this.canPress = true; }, this.props.pressTimeout || 500);
    }
  }
....
like image 50
Richard Lucas Avatar answered Dec 02 '25 04:12

Richard Lucas


If you are using stack navigator then what react-navigation does is for each navigation.navigate it pushes the route in the stack so in your case stack will fill in this way

  1. STACK [Route1]

  2. STACK [Route2,Route1] . // componentDidMount will be called once printing 1

  3. STACK [Route1,Route2,Route1]

  4. STACK [Route2, Route1, Route2, Route1] // whereas here componentDidMount will be called once for each pushed routes, printing 1 and 2 for both routes in the stack

So there will be two Route2 in the stack with different params.

That is the way react-navigation.

So instead of using navigate everytime, you can use following options as well according to your needs :

  • pop - go back in the stack
  • popToTop - go to the top of the stack
  • replace - replace the current route with a new one
like image 21
Rajat Gupta Avatar answered Dec 02 '25 05:12

Rajat Gupta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!