了解如何在 Expo Router 中重定向 URL。
你可以根据某些应用内条件将请求重定向到不同的 URL。Expo Router 支持多种不同的重定向模式。
¥You can redirect a request to a different URL based on some in-app criteria. Expo Router supports a number of different redirection patterns.
Redirect
组件¥Using Redirect
component
你可以使用 Redirect
组件立即从特定屏幕重定向:
¥You can immediately redirect from a particular screen by using the Redirect
component:
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>Welcome Back!</Text>
</View>
);
}
useRouter
钩子¥Using useRouter
hook
你还可以使用 useRouter
钩子强制重定向:
¥You can also redirect imperatively with the useRouter
hook:
import { Text } from 'react-native';
import { useRouter, useFocusEffect } from 'expo-router';
function MyScreen() {
const router = useRouter();
useFocusEffect(() => {
// Call the replace method to redirect to a new route without adding to the history.
// We do this in a useFocusEffect to ensure the redirect happens every time the screen
// is focused.
router.replace('/profile/settings');
});
return <Text>My Screen</Text>;
}