React Navigation v6如何监听goBack事件?v4升级适配问题
方案1:通过跳转传参,在目标页面返回时触发回调
你可以延续传回调的思路,调整参数传递方式并修正TypeScript类型问题:
- 跳转时传递回调参数
// 类组件写法 this.props.navigation.navigate('EditAccount', { onGoBack: () => this.onRefresh(), });
- 在
EditAccount页面返回前执行回调
// 类组件写法 handleGoBack = () => { // 先执行回调再返回 this.props.route.params?.onGoBack?.(); this.props.navigation.goBack(); };
- 修正TypeScript类型报错
为路由参数定义类型,避免类型检查报错:
// 定义全局路由参数类型 type RootStackParamList = { EditAccount: { onGoBack?: () => void; }; // 其他路由参数定义... }; // 为类组件的props指定类型 import { NavigationProp, RouteProp } from '@react-navigation/native'; type CurrentScreenNavigationProp = NavigationProp<RootStackParamList, '当前页面路由名'>; type CurrentScreenRouteProp = RouteProp<RootStackParamList, '当前页面路由名'>; class YourComponent extends React.Component<{ navigation: CurrentScreenNavigationProp; route: CurrentScreenRouteProp; }> { // 组件逻辑... }
方案2:监听当前页面的focus事件(官方推荐)
React Navigation v6中,从其他页面返回时,当前页面会触发focus事件,直接监听这个事件就能实现返回后的刷新逻辑:
类组件实现
componentDidMount() { // 订阅focus事件 this.focusListener = this.props.navigation.addListener('focus', () => { this.onRefresh(); }); } componentWillUnmount() { // 取消订阅,避免内存泄漏 this.focusListener?.(); }
函数组件实现
import { useFocusEffect } from '@react-navigation/native'; import { useCallback } from 'react'; useFocusEffect( useCallback(() => { onRefresh(); }, []) );
补充说明
React Navigation v6的addListener仅支持focus、blur、state、beforeRemove四种事件,确实没有专门的goBack事件。因为返回操作本质会触发上一页的focus事件,所以用focus监听是官方推荐的替代方案,更符合v6的设计逻辑。
内容的提问来源于stack exchange,提问作者DLateef
相关产品推荐
相关产品推荐

