javascript 如何从React导航中获取以前的路由名称

os8fio9y  于 2023-03-28  发布在  Java
关注(0)|答案(8)|浏览(235)

我试图得到以前的路线名称到我的当前屏幕。因为基于以前的屏幕名称,我必须显示/隐藏当前屏幕中的一些对象。
为了获取以前的屏幕名称,我尝试了以下操作

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
有什么建议吗?

juud5qan

juud5qan1#

对于Stack Navigators,我能够在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

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

if (prevRoute.name === "<Some Routing Key>") {
      navigation.navigate("<Some Routing Key>", params);
}
vmpqdwk3

vmpqdwk32#

您需要使用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中调用上述函数

<Text onPress={this.goToScreen}>Go to screen</Text>

在另一个屏幕上

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

Working demo
功能版本

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

并访问参数,如

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

  return ....
}
piv4azn7

piv4azn73#

我得到了正确的方式找到以前的路线(屏幕)名称从当前屏幕

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

谢谢大家-K 00 L;)

zwghvu4y

zwghvu4y4#

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

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;
  }
}
332nm8kg

332nm8kg5#

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

x8diyxa76#

使用react-navigation v5,你可以使用路由和索引递归导航状态来找到当前路由。一旦你找到了当前路由,一个没有任何子路由的对象,你可以从索引中减去1来获得前一个路由。
实现这一点的代码类似于

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
}

这种策略有一些限制-由于堆栈的限制,它会在返回时返回当前路线。它也会在切换堆栈时返回当前屏幕。

cyvaqqii

cyvaqqii7#

app.js | index.js中定义一些函数。表示初始屏幕

setActiveScreen = (activeScreen) => { 
    const previousScreen = this.state.activeScreen
    this.setState({activeScreen: activeScreen, previousScreen: previousScreen})
  }
  goBackScreen = () => {
    this.setState({activeScreen: this.state.previousScreen});
  }

并将此功能传递到导航屏幕

<Stack.Screen >   
{(props) => <ComponentScreen goBackScreen={this.goBackScreen} setActiveScreen={this.setActiveScreen} /> }
</Stack.Screen>

然后在屏幕中使用navigation.goBack()之前运行goBackScreen

<TouchableOpacity onPress={() => {
this.props.goBackScreen()
this.props.navigation.goBack();
}}><Text>Click</Text> </TouchableOpacity>

Note:现在你可以在activeScreen中获得以前的屏幕名称。这只是一个可能性的例子。你可以尝试自己的想法
或者可以在params中传递上一个屏幕

navigation.navigate("home", {params: {previousScreen: '{{pass the currentScreen name}}'

然后下一个屏幕你可以得到它的console.log(this.props.route.params)

8aqjt8rx

8aqjt8rx8#

使用navigation ref,您可以访问根状态。
此块帮助检查目标路由是否位于嵌套导航/路由(currentRoute?.state?.index > -1 && currentRoute?.state?.routes) ? currentRoute?.state?.routes?.[currentRoute?.state?.index]

const getRecentRoutes = ()=> {
        const rootState = navigationContainerRef.current?.getRootState();
        const routes = rootState?.routes;
        const previousRoute = routes?.[routes?.length - 2];
        const currentRoute = routes?.[routes?.length - 1];
        return {
          currentRoute: (currentRoute?.state?.index > -1 && currentRoute?.state?.routes) ? currentRoute?.state?.routes?.[currentRoute?.state?.index] : currentRoute,
          previousRoute: (previousRoute?.state?.index > -1 && previousRoute?.state?.routes) ? previousRoute?.state?.routes?.[previousRoute?.state?.index] : previousRoute,
        };
      };

相关问题