53 lines
1.3 KiB
TypeScript
53 lines
1.3 KiB
TypeScript
import { useRouter, useSegments } from 'expo-router'
|
|
import { useEffect } from 'react'
|
|
|
|
import { userStore } from '@/stores'
|
|
|
|
const PUBLIC_ROUTES = [
|
|
'', // 根路径
|
|
'(tabs)', // tabs 布局
|
|
'index', // 首页(探索页)
|
|
'auth', // 登录注册页
|
|
'pointList', // 积分列表页
|
|
'explore',
|
|
'forget-password',
|
|
]
|
|
|
|
function isPublicRoute(segments: string[]): boolean {
|
|
if (segments.length === 0) return true
|
|
|
|
const firstSegment = segments[0]
|
|
if (PUBLIC_ROUTES.includes(firstSegment)) return true
|
|
|
|
if (firstSegment === '(tabs)' && segments.length >= 2) {
|
|
const tabRoute = segments[1]
|
|
return tabRoute === 'index'
|
|
}
|
|
|
|
return false
|
|
}
|
|
|
|
export function useRouteGuard() {
|
|
// 从MobX Store获取用户状态
|
|
const { isAuthenticated, isLoading } = userStore
|
|
const segments = useSegments()
|
|
const router = useRouter()
|
|
|
|
console.log('userStore-----------------', { isAuthenticated, isLoading, segments })
|
|
|
|
useEffect(() => {
|
|
if (isLoading) return
|
|
|
|
const inPublicRoute = isPublicRoute(segments)
|
|
const inAuthRoute = segments[0] === 'auth'
|
|
|
|
if (!isAuthenticated && !inPublicRoute) {
|
|
router.replace('/auth')
|
|
} else if (isAuthenticated && inAuthRoute) {
|
|
router.replace('/(tabs)')
|
|
}
|
|
}, [isAuthenticated, isLoading, segments])
|
|
|
|
return { isAuthenticated, isLoading }
|
|
}
|