You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native Expo Router v2认证流程问题:切换栈后页面未跳转

Expo Tabs@49模板路由切换后停留在Auth页面的处理方案

结论先行:必须手动添加重定向逻辑,Expo Router 49版本不会自动根据栈切换跳转至新栈的初始页面,默认只会匹配目录结构中第一个出现的index路由作为初始入口。

具体解决步骤:

  1. 在Auth登录页添加状态判断与重定向
    在(auth)/index组件中,通过你的Auth上下文获取登录状态,当用户已认证时,使用useRouter的replace方法跳转到Tabs栈的首页:

    import { useEffect } from 'react';
    import { useRouter } from 'expo-router';
    import { useAuth } from '../context';
    
    export default function AuthIndex() {
      const { isAuthenticated } = useAuth();
      const router = useRouter();
    
      useEffect(() => {
        if (isAuthenticated) {
          // 跳转到Tabs栈首页,replace避免返回Auth页
          router.replace('/(tabs)/index');
        }
      }, [isAuthenticated]);
    
      // 未登录时渲染登录表单
      return (
        // 你的登录UI代码
      );
    }
    
  2. 确认Root Layout的栈配置逻辑
    确保app/_layout中是根据登录状态切换渲染对应的栈,示例如下:

    import { Stack } from 'expo-router';
    import { useAuth } from './context';
    
    export default function RootLayout() {
      const { isAuthenticated } = useAuth();
    
      return isAuthenticated ? (
        <Stack screenOptions={{ headerShown: false }}>
          <Stack.Screen name="(tabs)" />
        </Stack>
      ) : (
        <Stack screenOptions={{ headerShown: false }}>
          <Stack.Screen name="(auth)" />
        </Stack>
      );
    }
    

    注意:这里的栈切换只是控制渲染哪个路由分支,并不会自动重置路由到新分支的首页,所以必须配合第一步的重定向逻辑。

  3. 关于空白项目自动跳转第一个index的问题
    这是Expo Router的默认机制:它会按目录遍历顺序,把第一个找到的index路由作为应用初始入口。所以如果(auth)/index在目录结构中优先级高于(tabs)/index,就会默认加载它,这属于正常行为。

内容的提问来源于stack exchange,提问作者Vítor Fraporti Rosmann

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 03:27:41