如何从 React Navigation 获取以前的路线名称

Ani*_*ive 7 javascript react-native react-navigation

我正在尝试将以前的路线名称放到当前屏幕上。因为基于之前的屏幕名称,我必须在当前屏幕中显示/隐藏一些对象。

为了获得以前的屏幕名称,我尝试了以下

componentDidMount() {
    const { navigation } = this.props;
    if (navigation.state.params && navigation.state.params.previous_screen) {
       console.log('navigation.state.params.previous_screen', navigation.state.params.previous_screen);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,它正在undefined进入控制台日志。

有什么建议?

Con*_*amb 23

对于 Stack Navigator,我可以使用以下命令动态获取 React-navigation v6 中之前的路由名称:

// `navigation` const is passed to the screen component or from useNavigation()
const routes = navigation.getState()?.routes;
const prevRoute = routes[routes.length - 2]; // -2 because -1 is the current route
Run Code Online (Sandbox Code Playgroud)

注意:这对于动态地将参数传递回上一个屏幕非常有用。但要注意嵌套路由,语法略有不同。

if (prevRoute.name === "<Some Routing Key>") {
      navigation.navigate("<Some Routing Key>", params);
}
Run Code Online (Sandbox Code Playgroud)

  • 更好的方法是使用“useNavigationState”挂钩,因为他们建议不要以这种方式使用“navigation.getState()?.routes;”。[文档](https://reactnavigation.org/docs/use-navigation-state) (3认同)

Ten*_*ter 9

你需要使用NavigationActions

goToScreen = () => {

  const navigateAction = NavigationActions.navigate({
    routeName: 'Profile',

    params: { previous_screen: 'Home' }, // current screen

    action: NavigationActions.navigate({ routeName: 'Profile' }), // screen you want to navigate to
  });

  this.props.navigation.dispatch(navigateAction);
  
};
Run Code Online (Sandbox Code Playgroud)

在你的中调用上面的函数onPress

<Text onPress={this.goToScreen}>Go to screen</Text>
Run Code Online (Sandbox Code Playgroud)

在您的另一个屏幕上

componentDidMount = () => {
  
  const { navigation } = this.props;
  if (navigation.state.params && navigation.state.params.previous_screen) {

    this.setState({
      previous_screen: navigation.state.params.previous_screen
    });

  } else {
    console.log("ERROR");
  }
};
Run Code Online (Sandbox Code Playgroud)

工作演示

功能版本

const goToScreen = () => {
  // assuming that navigation is passed in props
  props.navigation.navigate('Settings', {
    previous_screen: 'Home'
  })
}
Run Code Online (Sandbox Code Playgroud)

并访问参数,例如

const Settings = ({ route }) => {
  const { previous_screen } = route.params;

  return ....
}
Run Code Online (Sandbox Code Playgroud)


小智 5

我得到了从当前屏幕找到上一条路线(屏幕)名称的正确方法

 props.navigation.dangerouslyGetParent().state.routes 
Run Code Online (Sandbox Code Playgroud)

您将从导航堆栈中获取屏幕列表(数组)。像这样的例子

输出在这里

Array(0) [, …]
0:Object {routeName: "ROUNTE_NAME", key: "id-158*****6785-1"}
1:Object {params: Object, routeName: "Screen1", key: "Screen1"}
2:Object {params: Object, routeName: "Screen2", key: "Screen2"}
Run Code Online (Sandbox Code Playgroud)

谢谢你们 - K00L ;)