react-navigation 3 reset in nested stack
Your resetAction
is unsuccessful because you are dispatching it on TabStack
(because you are calling this.props.navigation.dispatch
on UserProfile
, if I get you correctly). You need to dispatch the resetAction
to your MainStack
instead. This thread here suggested some ways that you can achieve this. And also, here is my preferred solution, because i don't have to pass props around navigators or calls multiple nested actions with this.
- Create a
navigationService.js
with the following contents (to keep your top level navigator as a reference)
import { NavigationActions, StackActions } from 'react-navigation';
let _navigator;
function setTopLevelNavigator(navigatorRef) {
_navigator = navigatorRef;
}
function navigateMainNavigator(routeName, params) {
_navigator.dispatch(
NavigationActions.navigate({
routeName,
params,
}),
);
}
// add other navigation functions that you need and export them
export default {
setTopLevelNavigator,
navigateMainNavigator,
};
- On your
App.js
or any other file you render yourMainStack
, do this to set the reference
import NavigationService from './navigationService';
...
render() {
return (
...
<MainStack
ref={navigatorRef => {
NavigationService.setTopLevelNavigator(navigatorRef);
}}
/>
...
)
}
- And wherever when you want to reset to your
AuthStack
(or any other stack in yourMainStack
), just importNavigationService
and call
NavigationService.navigateAndReset('Auth', {...yourParamsIfAny});
// 'Auth' because you named it that way in your 'MainStack'
===========================================================================
Edited
Previous solution, in navigationService.js
, is for StackNavigator
as the MainStack
function navigateAndReset(routeName, params) {
_navigator.dispatch(
StackActions.reset({
index: 0,
actions: [
NavigationActions.navigate({
routeName,
params,
}),
],
})
);
}