Reputation: 18719
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?
Upvotes: 3
Views: 2111
Reputation: 1954
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
STACK [Route1]
STACK [Route2,Route1] . // componentDidMount will be called once printing 1
STACK [Route1,Route2,Route1]
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 :
Upvotes: 1
Reputation: 103
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);
}
}
....
Upvotes: 1