參考Native的聲明周期,你會發(fā)現RN缺少生命周期Hook--進入和離開。
你會發(fā)現除了第一次加載,我們沒有辦法再獲取它進入頁面的時機,離開就壓根沒有...
基于HOC和react-native-router-flux庫改造RN生命周期击喂。
參考文章
custom-lifecycle-methods-in-react-native
React高階組件(HOC)模型理論與實踐
react-native-router-flux
廢話少說,直接上代碼
生命周期Wrapper
import { AppState } from 'react-native';
import React, { Component } from 'react';
export function withWrappedComponent(WrappedComponent) {
let componentInstance = null;
let activeStatus = false;
function componentWillAppear() {
if(componentInstance && componentInstance.componentWillAppear && !activeStatus) {
componentInstance.componentWillAppear()
}
activeStatus = true;
}
function componentWillDisappear() {
if(componentInstance && componentInstance.componentWillDisappear && activeStatus) {
componentInstance.componentWillDisappear();
}
activeStatus = false;
}
return class WrapperComponent extends Component {
// 進入該組件時觸發(fā)碰辅,react-native-router-flux提供
static onEnter() {
componentWillAppear()
}
// 離開該組件時觸發(fā)懂昂,react-native-router-flux提供
static onExit() {
componentWillDisappear();
}
constructor(props) {
super(props);
activeStatus = true;
// 監(jiān)聽RN實例狀態(tài)改變
// 1. 切換到Native的頁面
// 2. APP前后臺切換(Home按鈕)
AppState.addEventListener('change', this._handleAppStateChange);
}
_handleAppStateChange = (nextAppState) => {
if (nextAppState === 'active') {
componentWillAppear()
} else {
componentWillDisappear();
}
}
componentDidMount() {
}
componentWillUnmount() {
AppState.removeEventListener('change', this._handleAppStateChange);
// componentInstance = null;
activeStatus = false;
}
handleInstance(c) {
Boolean(c) && (componentInstance = c);
}
render() {
return <WrappedComponent ref={ c => this.handleInstance(c)} {...this.props}/>
}
}
}
使用方式
前置條件
主項目根目錄下執(zhí)行
npm i --save-dev babel-plugin-transform-decorators-legacy
-
創(chuàng)建.babelrc文件,內容如下:
{ "presets": ["react-native"], "plugins": ["transform-decorators-legacy"] }
使用方法
import { withWrappedComponent } from 'xxx'
@withWrappedComponent
export class Home extends Component {
componentWillAppear() {
console.log("xxxxxxxxxxxx home componentWillAppear");
}
componentWillDisappear() {
console.log("xxxxxxxxxxxx home componentWillDisappear");
}
}
componentWillAppear在第二次進入該頁面/從后臺進入前臺觸發(fā)
componentWillDisappear在離開頁面時觸發(fā)/從前臺進入后臺觸發(fā)