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

时间:2019-05-01 20:53:59

标签: 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);
    }
}

但是,控制台日志中出现undefined

有什么建议吗?

5 个答案:

答案 0 :(得分:4)

我有正确的方法从当前屏幕中找到先前的路线(屏幕)名称

 props.navigation.dangerouslyGetParent().state.routes 

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

输出在这里

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"}

谢谢大家-K00L;)

答案 1 :(得分:0)

您需要使用$limit = (Get-Date).AddMinutes(5) while (... -or (Get-Date) -gt $limit) { Start-Sleep -Seconds 1 }

if ((Get-Service ...).Status -ne "Running") {
    return
}

在您的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);

};

在另一个屏幕上

onPress

Working demo

答案 2 :(得分:0)

const navigateAction = NavigationActions.navigate({
  routeName: 'Profile',
  action: NavigationActions.navigate({ routeName: 'Profile', params: { previous_screen: 'Home' } }),
});
this.props.navigation.dispatch(navigateAction);

答案 3 :(得分:0)

使用const getPreviousRouteFromState = (route: NavigationRoute) => { let checkRoute = null if (route.state && route.state.index > -1 && route.state.routes) { checkRoute = route.state.routes[route.state.index] if (checkRoute.state && checkRoute.state.routes) { return getPreviousRouteFromState(checkRoute) } const previousRouteIndex = route.state.index - 1 if (previousRouteIndex > -1) { checkRoute = route.state.routes[previousRouteIndex] } } return checkRoute } v5,您可以使用路线和索引来递归导航状态以找到当前路线。找到当前路径(没有任何子路径的对象)后,可以从索引中减去1以获得上一条路径。

实现此目的的代码类似于

{{1}}

此策略有一些限制-由于堆栈的限制,它将在导航时返回当前路线。切换堆栈时,它还会返回当前屏幕。

答案 4 :(得分:0)

我使用了以下方法。这可能不是最好的方法,但确实有效。

let routes = this.props.navigation.dangerouslyGetState().routes[0].state.history;
for (let idx = routes.length - 1; idx >= 0; idx--) {
  if (routes[idx].type == 'route') {
    let route = routes[idx].key;
    this.props.navigation.navigate(route.substr(0, route.indexOf('-')));
    break;
  }
}