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

如何在React Native Expo Router中设置非index.tsx的默认栈

Expo Router 设置非index.tsx为默认栈页面的问题解决

在React Native Expo Router中,想要将默认路由栈的起始页面设置为非index.tsx的page1.tsx,但运行后出现**Unmatched route (page could not be found)**错误,无法正常访问页面。

复现步骤

  • 执行npx create-expo-app@latest创建项目
  • 执行npm run reset-project重置项目
  • 修改app目录下的两个文件:_layout.tsx和page1.tsx

用户当前代码

_layout.tsx

import { Stack } from "expo-router";

export default function RootLayout() {
  return (
    <Stack>
      <Stack.Screen name="page1" options={{ title: "P1" }} />
    </Stack>
  );
}

page1.tsx

import { Text, View } from "react-native";

export default function Index() {
  return (
    <View
      style={{
        flex: 1,
        justifyContent: "center",
        alignItems: "center",
      }}
    >
      <Text>Edit app/index.tsx to edit this screen.</Text>
    </View>
  );
}

package.json 依赖

"dependencies": {
    "expo": "~52.0.19",
    "expo-router": "~4.0.13",
    "expo-web-browser": "~14.0.1",
    "react": "18.3.1",
    "react-dom": "18.3.1",
    "react-native": "0.76.5",
}

问题原因及解决方法

1. 核心原因

Expo Router 默认以app/index.tsx作为根路由的入口页面,当该文件不存在时,启动项目后无法匹配默认的/路径,从而抛出路由不匹配错误。

2. 解决方法一:添加重定向的index.tsx

在app目录下创建index.tsx,通过重定向直接跳转到page1:

import { Redirect } from 'expo-router';

export default function Index() {
  return <Redirect href="/page1" />;
}

此方法简单直接,启动后会自动跳转到page1页面,同时保留原有page1.tsx的路由配置。

3. 解决方法二:指定Stack初始路由

在_layout.tsx的Stack组件中,通过initialRouteName明确设置初始页面:

import { Stack } from "expo-router";

export default function RootLayout() {
  return (
    <Stack initialRouteName="page1">
      <Stack.Screen name="page1" options={{ title: "P1" }} />
    </Stack>
  );
}

注意:此方法仅指定了栈的初始页面,但用户直接访问/路径时仍会报错,因此建议配合上述重定向的index.tsx一起使用,覆盖所有访问场景。

4. 额外注意事项

  • 确保page1.tsx的文件名与路由名称完全一致,Expo Router基于文件系统生成路由,文件名直接对应路由路径。
  • 当前使用的expo-router@~4.0.13版本完全支持上述配置,无需升级依赖。

内容的提问来源于stack exchange,提问作者u2gilles

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 12:50:04