React Native 生命周期

React Native 生命周期

主要分为三个阶段:
实例化阶段、存在阶段、销毁阶段
React Native 生命周期

常用的是实例化阶段:
这个阶段负责组件的构建和展示的时间,需要我们根据几个函数的调用过程,控制好组件的展示和逻辑处理
React Native 生命周期

实例化阶段函数:

getDefaultProps:是固定不变的常量
在组件中,我们可以利用this.props获取在这里初始化它的属性,由于组件初始化后,再次使用该组件不会调用getDefaultProps函数,所以组件自己不可以修改props,只可由其他组件调用它时再外部进行修改。

getIntialState:放可以改变的一些值
该函数用于对组件一些状态进行初始化
该函数不同于getDefaultProps,在以后的过程中,会再次调用,所以可以将控制控件状态的一些变量放在这里初始化,比如控件上显示的文字,可以通过this.state来获取值,通过this.setState来修改state值。

constructor(props) {
    super(props)
    this.state = { title:'默认文字' }
  }
  textPress(value){
    // console.warn('点击成功')
    this.setState({
      title:value
    })
  }
  render() {
    return (
      <View style={styles.container}>
        <TouchableOpacity activeOpacity={0.5}
           onPress={()=>this.textPress('点击')}
           style={styles.textStyle}>
          <Text>我是文字。点击下看看吧</Text>
        </TouchableOpacity>
        <Text>{this.state.title}</Text>
      </View>
    );
  }

注意:一旦调用了this.setState方法,组件一定会调用render方法,对组件进行再次渲染,不过,React框架会根据DOM的状态自动判断是否需要真正渲染
componentWillMount: 组件将要被加载到视图之前调用,开发中无实际意义

render:通过,this.state和this.setState访问之前函数的值

componentDidMount: 在调用了render方法,组件加载成功并被成功渲染出来之后,所要执行的后续操作,一般都会在这个函数中进行,比如经常要面对的网络请求等加载数据复杂操作

存在阶段函数

shouldComponentUpdate:一般用于优化,可以返回false或true来控制是否进行渲染(true 的话进行下2步操作,false不会进行下去)
componentWillUpdate: 组件刷新前调用
componentDidUpdate:更新后

shouldComponentUpdate(nextProps, nextState){
    console.log(this.state.detailContent,'detailContent');
    if (this.state.count !== nextState.count) {
      console.warn("组件需要更新");
      return true;
    }
    return false;
  }

  componentWillUpdate(){
    console.warn("组件将要更新");
  }

  componentDidUpdate(){
    console.warn("组件更新完毕");
  }

componentWillReceiveProps:指父元素对组件的props或state进行了修改

// 在子组件中对父元素props或state的改变进行监听进行相应的操作
componentWillReceiveProps(nextProps){
    console.warn(this.props.detailContent,'this--->>componentWillReceiveProps');
    console.warn(nextProps.detailContent,'next--->>componentWillReceiveProps')
  }
// componentWillReceiveProps -> 改变后执行父组件中 shouldComponentUpdate -> componentWillUpdate -> componentDidUpdate

销毁阶段函数

componentWillUnmount :用于清理一些无用的内容,比如:清除定时器或不需要的监听事件

componentWillUnmount() {
        if(Platform.OS == 'android') {
             this.createlistener.remove();
        }
             this.preparlistener.remove();
             this.complelistener.remove();
        this.stop();
        this.putStudyStatus();
        clearInterval(nIntervod);
    }