expo-router 路由切换监听
在使用 Expo Router 时,监听路由切换可以帮助你在用户导航时执行特定的操作,比如记录页面访问、更新状态或触发动画等。Expo Router 基于 React Navigation,因此你可以使用 React Navigation 提供的钩子和事件来监听路由变化。
以下是一个简单的示例,展示如何在 Expo Router 中监听路由切换:
安装必要的依赖:
确保你已经安装了 @react-navigation/native
和 @react-navigation/stack
。
expo install @react-navigation/native @react-navigation/stack
设置导航容器:
在你的应用程序入口文件(例如 App.js
)中,设置导航容器。
import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import HomeScreen from './screens/HomeScreen';
import DetailsScreen from './screens/DetailsScreen';
const Stack = createStackNavigator();
function App() {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Details" component={DetailsScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
export default App;
监听路由变化:
在你的屏幕组件中,使用 useFocusEffect
或 useEffect
钩子来监听路由变化。
import React, { useEffect } from 'react';
import { View, Text } from 'react-native';
import { useNavigation, useFocusEffect } from '@react-navigation/native';
function HomeScreen() {
const navigation = useNavigation();
useFocusEffect(
React.useCallback(() => {
console.log('Home Screen is focused');
return () => {
console.log('Home Screen is unfocused');
};
}, [])
);
return (
<View>
<Text>Home Screen</Text>
</View>
);
}
function DetailsScreen() {
const navigation = useNavigation();
useFocusEffect(
React.useCallback(() => {
console.log('Details Screen is focused');
return () => {
console.log('Details Screen is unfocused');
};
}, [])
);
return (
<View>
<Text>Details Screen</Text>
</View>
);
}
export { HomeScreen, DetailsScreen };
在这个示例中,我们使用了 useFocusEffect
钩子来监听屏幕的聚焦和失焦事件。当屏幕被聚焦时,会执行第一个回调函数;当屏幕失焦时,会执行返回的清理函数。
你也可以使用 useEffect
钩子来监听导航状态的变化:
import React, { useEffect } from 'react';
import { View, Text } from 'react-native';
import { useNavigationState } from '@react-navigation/native';
function HomeScreen() {
const navigationState = useNavigationState(state => state);
useEffect(() => {
console.log('Navigation state changed:', navigationState);
}, [navigationState]);
return (
<View>
<Text>Home Screen</Text>
</View>
);
}
export default HomeScreen;
通过这些方法,你可以在 Expo Router 中监听路由切换,并在导航状态变化时执行相应的