I think I can answer the question.
We have three pages:home page1 page2.
"home" is the "initialRouteName",and "page1" and "page2" is child pages.
So when we start with home,and push page1 (or navigate page1),the page stack is:
(2). page1
(1). home
and I push three times page2,the stack is:
(5). page2
(4). page2
(3). page2
(2). page1
(1). home
Now I want to go home, I can
1 pop Four times, or pop(4) directly;
2 navigate page1, then pop one time;
3 popToTop one time;
when page stack has no page1,navigate works the same as push,push page to top of stack and show the page.
when page stack has page1,the function of navigate is to jump to the page1 which is closest to the top of the stack,and pop others pages above page1.
For example, the following page stack:
(7). page2
(6). page2
(5). page2
(4). page1
(3). page1
(2). page1
(1). home
If you wan to go back to home,you should navigate page1 firstly ,then pop three times.
Tt should be noted that when current page is page1 and you navigate to page1,nothing
happened.
Here are some of the tests code I wrote,you just copy to App.js.
import * as React from 'react';
import { Button, View,Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
function HomeScreen({ navigation }) {
return (
<View style={{}}>
<Button
title="navigate to page1"
onPress={() => navigation.navigate('page1',{"pageName":"page1"})}
/>
<Button
title="push to page1"
onPress={() => navigation.push('page1',{"pageName":"page1"})}
/>
</View>
);
}
function Page({route, navigation }) {
return (
<View style={{}}>
<Text>{`current page is ${route.name}`}</Text>
<Button
title="navigate to Page1"
onPress={() => navigation.navigate('page1')}
/>
<Button
title="push Page1"
onPress={() => navigation.push('page1')}
/>
<Button
title="navigation to Page2"
onPress={() => navigation.push('page2')}
/>
<Button
title="push Page2"
onPress={() => navigation.push('page2')}
/>
<Button
title="Go to HomeScreen"
onPress={() => navigation.navigate('Home')}
/>
<Button
title="pop"
onPress={() => navigation.pop()}
/>
<Button
title="popToTop"
onPress={() => navigation.popToTop()}
/>
</View>
);
}
const Stack = createStackNavigator();
function MyStack() {
return (
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="page1" component={Page} />
<Stack.Screen name="page2" component={Page} />
</Stack.Navigator>
);
}
export default function App() {
return (
<NavigationContainer>
<MyStack />
</NavigationContainer>
);
}
I hope it will be helpful to you.