从反应导航堆栈中删除最后一条路线

时间:2017-09-27 21:21:02

标签: reactjs react-native react-navigation

所以,我有以下屏幕:

- ChatList
- NewRoom
- ChatRoom

基本上,我不想从刚刚创建的聊天室返回Start a new chat ...而是直接进入聊天室列表。到目前为止,我想出了以下内容:

const prevGetStateForActionChatStack = ChatStack.router.getStateForAction

ChatStack.router.getStateForAction = (action, state) => {
    if (state && action.type === 'RemovePreviousScreen') {
        const routes = state.routes.slice( 0, state.routes.length - 2 ).concat( state.routes.slice( -1 ) )
        return {
            ...state,
            routes,
            index: routes.length - 1
        }
    }
    return prevGetStateForActionChatStack(action, state)
}

它在理论上有效...但是在到达新房间后删除前一条路线时有一个奇怪的动画,如下所示。如果你们对这个问题有任何解决方案,请告诉我......

Example

3 个答案:

答案 0 :(得分:3)

在@ 3.0的反应导航中

import { StackActions, NavigationActions } from 'react-navigation';

const resetAction = StackActions.reset({
    index: 0,
    actions: [NavigationActions.navigate({ routeName: 'Profile' })],
});
this.props.navigation.dispatch(resetAction);

https://reactnavigation.org/docs/en/stack-actions.html#reset

答案 1 :(得分:1)

您的代码似乎正在使用react-navigation

React-Navigation有一个重置操作,允许您设置屏幕堆栈。 例如: 在你的情况下,

屏幕1:聊天室

屏幕2:聊天列表

如果要从堆栈中删除聊天室屏幕,则需要将其写为

import { NavigationActions } from 'react-navigation'

const resetAction = NavigationActions.reset({
  index: 0,
  actions: [
    NavigationActions.navigate({ routeName: 'chatlist'})
  ]
})
this.props.navigation.dispatch(resetAction)

这会将您的堆栈重置为仅一个屏幕作为聊天列表的初始屏幕。 actions数组可以有多个路由,index定义活动路由。

有关详细信息,请参阅以下链接:

https://reactnavigation.org/docs/navigators/navigation-actions

Resetting the navigation stack for the home screen (React Navigation and React Native)

答案 2 :(得分:0)

您应该能够使用以下内容更改动画:

export const doNotAnimateWhenGoingBack = () => ({
  // NOTE https://github.com/react-community/react-navigation/issues/1865 to avoid back animation
  screenInterpolator: sceneProps => {
    if (Platform.isIos) {
      // on ios the animation actually looks good! :D
      return CardStackStyleInterpolator.forHorizontal(sceneProps);
    }
    if (
      sceneProps.index === 0 &&
      sceneProps.scene.route.routeName !== 'nameOfScreenYouWannaGoTo' &&
      sceneProps.scenes.length > 2
    )
      return null;

    return CardStackStyleInterpolator.forVertical(sceneProps);
  },
});

并按如下方式使用:

const Stack = StackNavigator(
  {
  ...screens...
  },
  {
    transitionConfig: doNotAnimateWhenGoingBack,
  }
);
相关问题