React-Navigation-V6:获取当前聚焦屏幕标题并同步至Redux
全局监听路由变化实现Redux状态更新
不用在每个屏幕里写重复的useFocusEffect,可以通过全局监听导航容器的路由状态变化统一处理,具体实现如下:
实现思路
通过useNavigationContainerRef获取导航容器的引用,监听其state变化事件,每次路由切换时自动提取当前屏幕的标题,再dispatch到Redux中。同时处理应用启动的初始场景,确保首次加载时也能同步当前屏幕的标题。
代码示例
import { NavigationContainer, useNavigationContainerRef } from '@react-navigation/native'; import { useDispatch } from 'react-redux'; import { setReduxContent } from './your-redux-slice-path'; // 替换为你的slice文件路径 import DrawerNav from './your-drawer-navigator-path'; // 替换为你的Drawer导航组件 function App() { const navigationRef = useNavigationContainerRef(); const dispatch = useDispatch(); useEffect(() => { // 订阅路由状态更新事件 const unsubscribe = navigationRef.addListener('state', () => { syncScreenTitleToRedux(); }); // 应用启动时同步初始屏幕标题 syncScreenTitleToRedux(); // 组件卸载时取消订阅 return unsubscribe; }, [navigationRef, dispatch]); // 封装同步标题到Redux的逻辑 const syncScreenTitleToRedux = () => { const currentRoute = navigationRef.getCurrentRoute(); if (!currentRoute) return; // 兼容标题为动态函数的情况(静态字符串可直接简化为currentRoute.options.title) const screenTitle = typeof currentRoute.options.title === 'function' ? currentRoute.options.title({ route: currentRoute }) : currentRoute.options.title; if (screenTitle) { dispatch(setReduxContent(screenTitle)); } }; return ( <NavigationContainer ref={navigationRef}> <DrawerNav /> </NavigationContainer> ); }
注意事项
- 如果你的屏幕标题都是静态字符串,可以去掉
typeof判断逻辑,直接使用currentRoute.options.title。 - Drawer的展开/收起操作不会触发路由切换,因此不会重复执行dispatch,无需额外处理。
- 确保
navigationRef正确绑定到NavigationContainer,否则无法获取当前路由信息。
内容的提问来源于stack exchange,提问作者AndrewHoover898
相关产品推荐
相关产品推荐

