我有5个屏幕的StackNavigator(1)。在第三个屏幕之后,我导航到另一个StackNavigator(2)屏幕,并且在第二个StackNavigator(2)屏幕上执行了一些操作之后,我需要回到Stack StackNavigator(1)的第四个屏幕,并且应该能够返回到StackNavigator( 1)使用navigation.goBack()

我能够回到Stack StackNavigator(1)的第四个屏幕,但是当我使用navigation.goBack()时,它就不会回到StackNavigator(1)的第三个屏幕

我需要在StackNavigator(1)中保存和还原导航历史记录。

请让我知道有什么方法可以实现这一目标。

javascript - 有什么方法可以在react-navigation(react-native)中保存和还原导航历史记录-LMLPHP

最佳答案

使用StackNavigator.router.getStateForAction来处理您的路线状态。

    //assume your StackNavigator1 just like below
    const StackNavigator1 = new StackNavigator({
        Screen1: {screen: Screen1},
        Screen2: {screen: Screen2},
        Screen3: {screen: Screen3},
        Screen4: {screen: Screen4},
        Screen5: {screen: Screen5}
    });

    const defaultGetStateForAction = StackNavigator1.router.getStateForAction;
    //store the state when navigate to screen3
    let state3;

    StackNavigator1.router.getStateForAction = (action, state) => {

        let newState = defaultGetStateForAction(action, state);
        //print out the state object
        console.log(`newState: ${newState}`);

        //change all the routeName 'Screen3', 'Screen4' to match your own project
        if (action.type === 'Navigation/NAVIGATE' && action.routeName === 'Screen3') {
            //store the state of screen3 for restore it later
            state3 = newState;
        }

        if (action.type === 'Navigation/NAVIGATE' && action.routeName === 'Screen4') {
            //check if screen3 exist in the state, change the condition for your own need
            let result = newState.routes.find((route) => {
                return route.routeName === 'Screen3'
            });
            //if 'screen3' doesn't exist, add it to the route manually
            if (result === undefined && state3 !== undefined) {
                let route4 = newState.routes[newState.index];
                let routes = state3.routes.slice();
                routes.push(route4);
                return {index: 3, routes}
            }
        }

        return defaultGetStateForAction(action, state)
    };

//... the rest code

09-25 16:44