使用反应导航重置TabNavigator历史记录

时间:2017-05-03 14:34:07

标签: react-native react-navigation

我有以下结构:

    const routeConfiguration = {
        Login: { screen: Login },
        Home: { screen: TabBar },
    };

    const stackNavigatorConfiguration = {
        headerMode: 'screen',
        navigationOptions: {
            header: { visible: false }
        }
    };

export const RootNav = StackNavigator(routeConfiguration, stackNavigatorConfiguration);

我的TabBar,每个Tab都有自己的StackNavigator:

const routeConfiguration = {
    TabOneNavigation: { screen: TabOneNavigation },
    TabTwoNavigation: { screen: TabTwoNavigation },
    TabThreeNavigation: { screen: TabThreeNavigation },
};

const tabBarConfiguration = {
    tabBarOptions: {
        activeTintColor: 'white',
        inactiveTintColor: 'lightgray',
        labelStyle: {
            fontSize: 10,
            fontFamily: Fonts.book
        },
        style: {
            backgroundColor: Colors.greenLightGradient,
            borderTopWidth: 1,
            borderTopColor: Colors.tabGreenLine
        },
    }
};

export const TabBar = TabNavigator(routeConfiguration, tabBarConfiguration);

当应用程序首次加载时进入登录屏幕。成功登录后,我使用actionTypes.TO_HOME转到Home。我有3个标签(Feed,Suggestion,Profile)。在里面的配置文件选项卡我按下了注销按钮,我重置了导航历史记录并再次登录(到目前为止一直很好)。但是当我再次登录并转到Home时,它会显示第一个选项卡并导航我到最后一个(Profile),看起来TabNavigator的历史记录未被重置。我应该做一些特别的事情,以便TabNavigator的历史也被重置吗?

这是我的reducer,用于重置历史记录并进入登录屏幕:

export const navReducer = (state = initialState, action = {}) => {
    let nextState;
    switch (action.type) {
        case actionTypes.TO_LOGIN:
            nextState = RootNav.router.getStateForAction(
                NavigationActions.reset({
                    index: 0,
                    actions: [NavigationActions.navigate({ type: NavigationActions.NAVIGATE, routeName: actionTypes.TO_LOGIN })],
                    key: null
                }), state);
            break;

        case actionTypes.TO_HOME:
            nextState = RootNav.router.getStateForAction(
                NavigationActions.reset({
                    index: 0,
                    actions: [NavigationActions.navigate({ type: NavigationActions.NAVIGATE, routeName: actionTypes.TO_HOME })],
                }), state);
            break;

        default:
            nextState = RootNav.router.getStateForAction(action, state);
            break;
    }

    return nextState || state;
};

2 个答案:

答案 0 :(得分:0)

您可以将索引0置于导航操作

答案 1 :(得分:0)

这是一个React-Navigation v5示例,用于清除所有历史记录:

navigation.dispatch((state) => {
      return CommonActions.reset({
        ...state,
        history: state.history
          ? [
              state.history[
                state.history.length - 1
              ],
            ]
          : undefined,
      });
    });