Expo-Router嵌套路由栈异常:返回按钮始终显示Home Page
解决Expo Router嵌套路由导航栈统一问题
问题本质
你遇到的核心问题是子文件夹的_layout.tsx创建了独立导航栈,导致Settings与Auth页面分属不同栈实例:导航栏的返回逻辑仅关联根栈(Home所在栈),所以显示回到Home;但router.back()基于全局历史栈工作,因此能正确返回Settings。
解决方案
要实现统一的单个导航栈,需调整路由布局结构,避免子文件夹创建独立栈:
1. 配置根目录_layout.tsx
确保根布局使用Stack组件,将所有页面纳入同一个根栈:
// app/_layout.tsx import { Stack } from 'expo-router'; export default function RootLayout() { return ( <Stack screenOptions={{ headerBackTitleVisible: true, // 确保返回按钮显示正确的上一页标题 }} > <Stack.Screen name="Home" options={{ title: '首页' }} /> <Stack.Screen name="Settings" options={{ title: '设置' }} /> </Stack> ); }
2. 修改子文件夹_layout.tsx
在Settings文件夹的_layout.tsx中,用Slot替代Stack渲染子路由,让Auth页面直接加入根栈历史:
// app/Settings/_layout.tsx import { Slot } from 'expo-router'; export default function SettingsLayout() { return <Slot />; }
3. 可选:单独配置嵌套页面导航栏
如果需要给Auth页面单独设置导航栏选项,可在根栈中直接指定嵌套路由:
// app/_layout.tsx <Stack.Screen name="Settings/Auth" options={{ title: '认证页面', headerBackTitle: '设置' }} />
调整完成后,从Home→Settings→Auth的跳转流程中,导航栏返回按钮会正确显示回到Settings,与router.back()的行为完全一致。
内容的提问来源于stack exchange,提问作者Asif Iqbal
相关产品推荐
相关产品推荐

