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

时间:2017-08-16 11:56:51

标签: javascript reactjs react-native react-native-android react-native-ios

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

我能够回到Stack StackNavigator(1)第4屏幕但是当我使用navigation.goBack()时它不会去StackNavigator(1)第3屏幕

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

请告诉我有没有办法实现这一目标。

enter image description here

1 个答案:

答案 0 :(得分: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