我正在使用 expo-router 开发 React Native 项目,并且在基于会话状态的条件路由方面遇到问题。如果没有活动会话,我想导航到登录屏幕 (auth.tsx),或者如果用户已登录,则导航到基于选项卡的屏幕 ((tabs)/index.tsx)。
问题:
请帮帮我。
// app/_layout.tsx (this is the root layout)
import React, { useEffect } from 'react';
import { View, Text } from 'react-native';
import { Stack } from 'expo-router';
import { useAuth } from '../context/AuthContext';
function AppContent() {
const { session, isLoading } = useAuth();
if (isLoading) {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Loading...</Text>
</View>
);
}
return (
<Stack screenOptions={{ headerShown: false }}>
{!session || !session.user ? ( // this does not work
// Navigate to auth if session is null, undefined, or invalid
<Stack.Screen name="auth" options={{ headerShown: false }} />
) : (
// Navigate to (tabs) if session and user are valid
<Stack.Screen name="(tabs)" options={{ headerShown: false }} />
)}
</Stack>
);
}
export default function App() {
return (
<AuthProvider>
<AppContent />
</AuthProvider>
);
}
我已确保文件结构与 expo-router 约定匹配:
/app
├── auth.tsx // Login screen
├── _layout.tsx // Root layout
└── (tabs)
└── index.tsx // Tab-based screen
└── _layout.tsx // Tab-based layout
退出按钮:
<TouchableOpacity onPress={async () => {
try {
const { error } = await supabase.auth.signOut();
if (error) {
console.error('Error signing out:', error.message);
} else {
console.log('Successfully logged out');
// Sign out the user
await router.push('../../app/auth.tsx');
}
} catch (err) {
console.error('Unexpected error during sign out:', err);
}
}}>
<Text style={[styles.drawerItem, styles.logout]}>Logout</Text>
</TouchableOpacity>
<Button
title="Sign Out"
onPress={async () => {
await supabase.auth.signOut(); // Sign out the user
router.push('/app/Auth.tsx'); // Navigate to the Auth page
}}
color="#34d399"
/>
router.push('/app/Auth.tsx'); ===>router.push('/app/auth.tsx');