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

Edu*_*ard 6 reactjs react-native react-navigation

所以,我有以下屏幕:

- ChatList
- NewRoom
- ChatRoom
Run Code Online (Sandbox Code Playgroud)

基本上,我不想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)
}
Run Code Online (Sandbox Code Playgroud)

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

例子

小智 8

在 react-navigation@3.0

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

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

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

在 react-navigation@6.0

重置操作被替换替换。

import { StackActions } from '@react-navigation/native';

navigation.dispatch(   
    StackActions.replace('Profile', {user: 'jane',}) 
);
Run Code Online (Sandbox Code Playgroud)

https://reactnavigation.org/docs/stack-actions/#replace