[英]Wrong back button behavior in react native
伙計們,我有一個關於 React Native 導航的問題。 所以我主要使用TabNavigator。 我在應用程序中有 2 個主堆棧導航器
const Tab = createBottomTabNavigator();
export default function App() {
return (
<NavigationContainer>
<Tab.Navigator>
<Tab.Screen name="Home" component={HomeStackScreen} />
<Tab.Screen name="Profile" component={ProfileStackScreen} />
</Tab.Navigator>
</NavigationContainer>
);
}
在我的 ProfileStack 屏幕中,我還有兩個頁面:MyProfile 和 UsersProfile:
const ProfileStack = createNativeStackNavigator();
function ProfileStackScreen({route, navigation}) {
return (
<ProfileStack.Navigator initialRouteName="MyProfile">
<ProfileStack.Screen name="MyProfile" component={MyProfilePage} />
<ProfileStack.Screen name="UserProfile" component={UserProfilePage} options={{
headerLeft: () => (<View>
<Button title="back" onPress={() => {navigation.goBack()}}/>
</View>)
}}/>
</ProfileStack.Navigator>
);
}
現在我想從HomeScreen
導航到UserProfilePage
並將參數傳遞到這個屏幕。 我是這樣做的:
function HomeScreen({ navigation }) {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Home screen this</Text>
<Button
title="Go to another user profile"
onPress={() => navigation.navigate('Profile', {screen: 'UserProfile', params: {userId: 1235}})}
/>
</View>
);
}
所以現在,當我來到UserProfile
頁面時,我看到它也加載了Profile
頁面,就一秒鍾,我看到 ProfilePage 和它的 UI 不酷,它應該是這樣嗎? 我猜不是。 然后,如果我按下UsersProfilePage
上的 BACK 按鈕,我將導航回 HomeScreen - 這沒問題! 這是我所期待的!
但是現在,如果我按下ProfileTab
我只會看到UsersProfilePage
而不是MyProfilePage
。 當我再次按下BACK按鈕,我回到HomeScreen
是奇怪的我。 你能解釋為什么會這樣嗎? 為什么我不回到MyProfilePage
。
這是因為您要導航到嵌套導航器中的屏幕。 它忽略了初始路線。 然后當你再次按下選項卡時,它仍然處於掛載狀態,並且仍然具有之前的路由狀態,即沒有初始屏幕的屏幕。
默認情況下,當您在嵌套導航器中導航屏幕時,指定的屏幕將用作初始屏幕,並且導航器上的初始路由屬性將被忽略。 這種行為不同於 React Navigation 4。
如果需要渲染導航器中指定的初始路由,可以通過設置initial:false來禁用使用指定屏幕作為初始屏幕的行為:
navigation.navigate('Root', {
screen: 'Settings',
initial: false,
});
請參閱https://reactnavigation.org/docs/nesting-navigators/#rendering-initial-route-defined-in-the-navigator和https://reactnavigation.org/docs/navigation-lifecycle/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.