【问题标题】:Is there any way to save and restore the navigation history in react-navigation (react-native)有什么方法可以保存和恢复 react-navigation 中的导航历史(react-native)
【发布时间】:2018-01-24 13:25:30
【问题描述】:

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

我可以返回 Stack StackNavigator(1) 第 4 个屏幕,但是当我使用 navigation.goBack() 时,它不会返回 StackNavigator(1) 第 3 个屏幕

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

请让我知道有什么办法可以做到这一点。

【问题讨论】:

  • 嘿 Anish,我有类似的用例要实现。你能解决这个问题吗?
  • 你是如何解决这个问题的?

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


【解决方案1】:

使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-16
    • 1970-01-01
    • 1970-01-01
    • 2020-12-09
    • 2021-11-02
    • 1970-01-01
    • 2023-03-03
    相关资源
    最近更新 更多