React Native 生命周期

React Native 生命周期

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

经常使用的是实例化阶段:
这个阶段负责组件的构建和展现的时间,须要咱们根据几个函数的调用过程,控制好组件的展现和逻辑处理
经常使用的事件web

实例化阶段函数:

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: 组件将要被加载到视图以前调用,开发中无实际意义svg

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

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

存在阶段函数

shouldComponentUpdate:通常用于优化,能够返回false或true来控制是否进行渲染(true 的话进行下2步操做,false不会进行下去)
componentWillUpdate: 组件刷新前调用
componentDidUpdate:更新后this

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进行了修改spa

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

销毁阶段函数

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

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

本文同步分享在 博客“zoepriselife316”(CSDN)。
若有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一块儿分享。

相关文章
相关标签/搜索