有没有办法在react-navigation(react-native)中保存和恢复导航历史记录

Ani*_*ish 6 javascript reactjs react-native react-native-ios

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

我可以回到 Stack StackNavigator(1) 第四个屏幕,但是当我使用 navigation.goBack() 时,它不会转到 StackNavigator(1) 第三个屏幕

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

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

在此输入图像描述

ufx*_*eng 0

用于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
Run Code Online (Sandbox Code Playgroud)