如何导航到堆栈的顶部(在react-navigation-v5上)?

时间:2020-08-03 04:42:34

标签: react-native react-navigation react-navigation-stack react-navigation-v5

我要使用React-Navigation v5导航到堆栈的第一个屏幕(而不是我最后一次在该堆栈中访问的最后一个屏幕)。

我尝试使用dispatch(StackActions.popToTop())。但是,如果用户已经在堆栈顶部,则会导致错误!

错误是:The action 'POP_TO_TOP' was not handled by any navigator. Is there any screen to go back to? This is a development-only warning and won't be shown in production.

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

props.navigation.navigate("MyStack");

// The following works most of the time. However, it causes an error if the user is already on top of the stack! 
props.navigation.dispatch(StackActions.popToTop()); 

1 个答案:

答案 0 :(得分:0)

以下代码似乎有效。

但是,对于这样的基本(我认为)要求来说,这是很长的代码。我想知道是否有更简单的解决方案。

此外,它使用导航器的状态对象,文档不建议使用导航器的状态对象。在https://reactnavigation.org/docs/navigation-actions#reset上说,“ 将导航器的状态对象视为内部对象和主题。在次要版本中进行更改。

import { CommonActions } from "@react-navigation/native";

// more code...

props.navigation.dispatch(state => {
    // Find (by name) the stack, which I need to reset 
    let i; 
    for (i = 0; i < state.routes.length; i++) {
        if (state.routes[i].name === "MyStack") {
            break;
        }
    }
    // If there has been any activity for the stack, which we found above, we reset it 
    let routes2 = { ...state.routes };
    if (routes2[i].state) { 
        delete routes2[i].state;
    }
    return CommonActions.reset({
        ...state,
        routes2,
    });
});
props.navigation.navigate("MyStack");