React Native退出登录后导航时出现渲染错误求助
问题描述
开发的React Native应用包含SignIn、SignUp、Sign Out功能,退出登录逻辑为:通过AsyncStorage移除本地token → 分发action → 导航至loginFlow页面,但此时触发渲染错误。登录、注册时使用相同的navigate方法可正常工作,AuthContext使用navigationRef提供的导航实例。
错误详情
错误信息
TypeError: _reactNative.Dimensions.removeEventListener is not a function. (In '_reactNative.Dimensions.removeEventListener('change', this.handleOrientationChange)', '_reactNative.Dimensions.removeEventListener' is undefined)
错误调用栈
in withDimensions(undefined) (created by TabNavigationView)
in RCTView (created by View)
in View (created by TabNavigationView)
in TabNavigationView (created by NavigationView)
in NavigationView (created by Navigator)
in Navigator (created by SceneView)
in SceneView (created by SwitchView)
in SwitchView (created by Navigator)
in Navigator (created by NavigationContainer)
in NavigationContainer (created by _default)
in Provider (created by _default)
in _default (created by withDevTools(_default))
in withDevTools(_default)
in RCTView (created by View)
in View (created by AppContainer)
in RCTView (created by View)
in View (created by AppContainer)
in AppContainer
in main(RootComponent)
已尝试的排查步骤
- 在AuthContext中注释所有代码并打印日志,确认Sign Out的onPress调用了正确的函数;
- 替换导航目标为TrackList可成功完成导航,且本地token已清除,说明AsyncStorage功能正常,错误出在loginFlow页面的渲染逻辑;
- 尝试将导航回调作为props传入的旧方法,仍出现相同错误。
解决方案
1. 替换废弃的Dimensions事件监听API
React Native 0.65及以上版本中,Dimensions.removeEventListener已被废弃,需改用新的订阅式API:
错误写法:
Dimensions.removeEventListener('change', this.handleOrientationChange);
正确写法:
// 初始化时保存订阅引用 componentDidMount() { this.orientationSubscription = Dimensions.addEventListener('change', this.handleOrientationChange); } // 组件卸载时移除监听 componentWillUnmount() { this.orientationSubscription?.remove(); }
2. 适配导航库与RN版本
错误栈指向TabNavigationView,说明问题出在底部导航组件的实现:
- 若使用
react-navigation,确保@react-navigation/native版本与React Native版本兼容(RN≥0.65建议使用v6+版本); - 升级导航库到最新兼容版本,或手动修改导航组件中处理屏幕方向的代码,替换为新的Dimensions API。
3. 检查loginFlow的导航结构
确认loginFlow页面是否嵌套了Tab导航,且该导航组件使用了已废弃的removeEventListener方法。定位到withDimensions高阶组件相关代码,替换事件监听逻辑即可解决。
内容的提问来源于stack exchange,提问作者kp151095

