react-native生命周期改造

参考Native的声明周期,你会发现RN缺少生命周期Hook--进入离开
你会发现除了第一次加载,我们没有办法再获取它进入页面的时机,离开就压根没有...

基于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 {
    // 进入该组件时触发,react-native-router-flux提供
    static onEnter() {
      componentWillAppear()
    }

    // 离开该组件时触发,react-native-router-flux提供
    static onExit() {
      componentWillDisappear();
    }

    constructor(props) {
      super(props);
      activeStatus = true;

      // 监听RN实例状态改变
      // 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  this.handleInstance(c)} {...this.props}/>
    }
  }
}

使用方式

前置条件

  1. 主项目根目录下执行npm i --save-dev babel-plugin-transform-decorators-legacy

  2. 创建.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在第二次进入该页面/从后台进入前台触发
componentWillDisappear在离开页面时触发/从前台进入后台触发

你可能感兴趣的:(react-native生命周期改造)