事故现场
项目使用RN开发且用react-navigation做的导航,要想每个页面在显示时都调用某个逻辑,我需要在每个页面的如下生命周期做如下两件事情:
blurListener: any = null;
focusListener: any = null;
componentWillUnmount() {
this.blurListener && this.blurListener();
this.focusListener && this.focusListener();
}
componentDidMount() {
// 非导航页面
if(!this.props.navigation) {
this.refWraper.current?.componentFocus && this.refWraper.current?.componentFocus();
return;
}
// 屏幕失焦时会发出此事件
this.blurListener = this.props?.navigation?.addListener('blur', () => {
this.refWraper.current?.componentBlur && this.refWraper.current?.componentBlur();
});
// 当屏幕聚焦时会发出此事件
this.focusListener = this.props?.navigation?.addListener('focus', () => {
this.refWraper.current?.componentFocus && this.refWraper.current?.componentFocus();
});
}
写一次还好,类似需求的所有页面都要搞这么一堆,那就有点头疼了。 因此就搞了一个高阶组件,将上诉逻辑统一归置到高阶中,这样就给所有的页面增加了两个生命周期componentFocus
/componentBlur
所有的路由页面都套上该高阶组件是没有问题的,但如果一个组件既用做路由页面也用作普通组件,就会有如下两个问题:
- 该组件应该使用哪个生命周期
当该组件用做路由页面时,我们应该用componentFocus
还是componentDidMount
来初始话信息,只用前者,该组件作为普通组件不会调用,只用后者,该组件作为路由页面无法每次页面显示都调用。我是在上诉高阶里处理的,具体代码在【非导航页面】那块。 - ref的嵌套问题
当作为普通组件,父组件需要调用子组件的方法,我一般通过ref获取实例来引用,但因为高阶组件的存在我得先找到高阶组件的ref,在从高阶组价中找到真正组件的ref,接着进行函数调用。我不想搞的这么麻烦,就在高阶组件中增加了如下一行:refWraper = this.props.curRef || React.createRef<BlurFocusLifeCircle>();
我的crash就是因为做高阶优化时忘了将ref指向真正的组件
ref的历史变化
TODO