1- import { Href , Redirect , SplashScreen } from 'expo-router' ;
1+ import { router , SplashScreen } from 'expo-router' ;
22import { getItem , setItem } from 'expo-secure-store' ;
33import * as React from 'react' ;
44import { Platform } from 'react-native' ;
@@ -8,61 +8,45 @@ import useCourse from '@/store/course';
88import { setupGlobalErrorHandler } from '@/utils/errorHandler' ;
99import { updateCourseData } from '@/utils/updateWidget' ;
1010
11- // 由于 expo 没有 initialRoutes
12- // 重定向到 tabs
13- // 详情见 issue: https://github.com/expo/router/issues/763#issuecomment-1635316964
1411const Index = ( ) => {
15- const [ initialRoute , setInitialRoute ] = React . useState < string | null > ( null ) ;
1612 const hydrated = useCourse ( state => state . hydrated ) ;
13+ const initialized = React . useRef ( false ) ;
1714
1815 React . useEffect ( ( ) => {
19- // if (__DEV__) {
20- // //console.log('mock server setup');
21- // setupMockServer();
22- // }
16+ if ( ! hydrated || initialized . current ) return ;
17+ initialized . current = true ;
2318
2419 const init = async ( ) => {
25- const firstLaunch = await getItem ( 'firstLaunch' ) ;
26-
27- const token = await getItem ( 'longToken' ) ;
28-
29- // 设置全局错误处理器
30- setupGlobalErrorHandler ( ) ;
31- // 等待 AsyncStorage 加载
32- if ( hydrated ) await SplashScreen . hideAsync ( ) ;
33- if ( ! token ) {
34- if ( firstLaunch === null ) {
35- // 是首次启动,设置标记并跳转到guide
36- setItem ( 'firstLaunch' , 'false' ) ;
37- setInitialRoute ( '/auth/guide' ) ;
38- } else {
39- if ( Platform . OS === 'android' ) {
40- updateCourseData ( )
41- . then ( ( ) => {
42- console . log ( 'updateWidget' ) ;
43- } )
44- . catch ( error => {
45- console . error ( '更新小组件失败:' , error ) ;
46- } ) ;
20+ try {
21+ const firstLaunch = await getItem ( 'firstLaunch' ) ;
22+ const token = await getItem ( 'longToken' ) ;
23+
24+ setupGlobalErrorHandler ( ) ;
25+ await SplashScreen . hideAsync ( ) ;
26+
27+ if ( ! token ) {
28+ if ( firstLaunch === null ) {
29+ setItem ( 'firstLaunch' , 'false' ) ;
30+ console . log ( '首次启动,跳转到引导页' ) ;
31+ router . replace ( '/auth/guide' ) ;
32+ } else if ( Platform . OS === 'android' ) {
33+ updateCourseData ( ) . catch ( error =>
34+ console . error ( '更新小组件失败:' , error )
35+ ) ;
36+ } else {
37+ router . replace ( '/auth/login' ) ;
4738 }
48-
49- // 不是首次启动但没有token,去登录
50- setInitialRoute ( '/auth/guide' ) ;
39+ } else {
40+ router . replace ( '/(tabs)' ) ;
5141 }
52- } else {
53- // 有token直接进入主页
54- setInitialRoute ( '/(tabs)' ) ;
42+ } catch ( error ) {
43+ console . error ( '初始化失败:' , error ) ;
5544 }
5645 } ;
5746
58- SplashScreen . preventAutoHideAsync ( ) ;
5947 init ( ) ;
6048 } , [ hydrated ] ) ;
6149
62- if ( ! initialRoute ) {
63- return null ;
64- }
65-
66- return < Redirect href = { initialRoute as Href } > </ Redirect > ;
50+ return null ;
6751} ;
6852export default Index ;
0 commit comments