重定向
编辑页面
了解如何在 Expo Router 中重定向 URL。
For the complete documentation index, see llms.txt. Use this Use this file to discover all available pages.
你可以根据某些应用内条件将请求重定向到不同的 URL。Expo Router 支持多种不同的重定向模式。
使用 Redirect 组件
你可以使用 Redirect 组件立即从特定屏幕进行重定向:
import { View, Text } from 'react-native'; import { Redirect } from 'expo-router'; export default function Page() { const { user } = useAuth(); if (!user) { return <Redirect href="/login" />; } return ( <View> <Text>欢迎回来!</Text> </View> ); }
使用 useRouter 钩子
你也可以通过 useRouter 钩子以命令式方式进行重定向:
import { Text } from 'react-native'; import { useRouter, useFocusEffect } from 'expo-router'; function MyScreen() { const router = useRouter(); useFocusEffect(() => { // 调用 replace 方法以重定向到新路由,而不会将其添加到历史记录中。 // 我们在 useFocusEffect 中这样做,以确保每次屏幕获得焦点时 // 都会发生重定向。 router.replace('/profile/settings'); }); return <Text>我的屏幕</Text>; }