I'm building a react native app there is login logout of user features.
I want to reset my main StackNavigator
when user logout from system and move on login screen.
I'm getting issue when i reset my main StackNavigator
from drawer menu.
here is my code,
const OrderStack = createStackNavigator({
Orders: {
screen: Orders,
},
OrderDetails: {
screen: OrderDetails,
},
DeliveryStatus: {
screen: DeliveryStatus,
},
DeliveryInstructions: {
screen: DeliveryInstructions,
},
ProductDetails: {
screen: ProductDetails,
},
});
const DrawerNavigations = createDrawerNavigator({
Home: OrderStack,
Location: {
screen: createStackNavigator({
Location: {
screen: Location,
},
}),
}
});
const RootStack = createStackNavigator(
{
Login: {
screen: Login,
},
Home: {
screen: DrawerNavigations,
}
},
{
initialRouteName: 'Login',
headerMode: 'none',
navigationOptions: {
headerVisible: false,
}
},
);
const AppNavigator = createAppContainer(RootStack);
export default class Main extends Component{
render() {
return (
<AppNavigator
ref={navigatorRef => {
NavigationService.setTopLevelNavigator(navigatorRef);
}}
/>
)
}
}
my logout
button code,
const resetAction = StackActions.reset({
index: 0,
actions: [NavigationActions.navigate({ routeName: 'Login' })],
});
this.props.navigation.dispatch(resetAction)
navigationService.js
import { NavigationActions, StackActions } from 'react-navigation';
let _navigator;
function setTopLevelNavigator(navigatorRef) {
_navigator = navigatorRef;
}
function navigateAndReset(routeName){
_navigator.dispatch(
StackActions.reset({
index: 0,
actions: [
NavigationActions.navigate({
routeName,
}),
],
})
);
}
export default {
setTopLevelNavigator,
navigateAndReset,
};
Thanks in Advanced! :)
答案 0 :(得分:0)
您的resetAction
不成功,因为您正在将操作分派到OrderStack
上。您需要将resetAction
调度到RootStack
。 This thread here提出了一些有趣的方法可以实现这一目标,请阅读。
而且,这是我的首选解决方案。因此,我不必在导航器周围传递道具或调用多个嵌套动作。
navigationService.js
(以使您的顶级导航器作为参考)import { NavigationActions, StackActions } from 'react-navigation';
let _navigator;
function setTopLevelNavigator(navigatorRef) {
_navigator = navigatorRef;
}
function navigateAndReset(routeName, params) {
_navigator.dispatch(
StackActions.reset({
index: 0,
actions: [
NavigationActions.navigate({
routeName,
params,
}),
],
})
);
}
// add other navigation functions that you need and export them
export default {
setTopLevelNavigator,
navigateAndReset,
};
App.js
或任何其他文件上渲染AppNavigator
(或RootStack
),导入NavigationService
并设置对AppNavigator
的引用import NavigationService from './navigationService';
...
render() {
return (
...
<AppNavigator
ref={navigatorRef => {
NavigationService.setTopLevelNavigator(navigatorRef);
}}
/>
...
)
}
Login
页面,只需导入NavigationService
并致电NavigationService.navigateAndReset('Login', {...yourParamsIfAny});