RN 组件 生命周期Lifecircle

为了合理开发,理理Lifecircle

@1、创建阶段:创建组件类时

// 初始化组件的默认属性defaultProps和属性类型propTypes
static  defaultProps = {
    autoPlay: false
};
static  propTypes = {
    autoPlay: React.PropsTypes.bool.isRequired
};
// 使用初始化组件,用this.props,组件内部props只读不可修改,若需要改变props,需其他组件调用时修改

@2、实例化阶段:组件类被调用的时候,触发一系列流程

// 一、构造器函数,初始化控制控件状态的一些变量
constructor(props){
    super(props);
    this.state = {
        mag: ''
    }
}

// 二、准备加载组件:生命周期只执行1次,在render之前渲染
componentWillMount(){
//初始化一些操作
    static setImageEmpty(){
        allTotalImage=[{hasImage: false, title: '综合照片', imageUrl: ''}]
        ···
    }
}

// 三、组件第一次渲染,渲染界面,并返回JSX或其他组件构成Dom,只能返回一个顶级元素
render(){
    return(
        <View></View>
    )
}

// 四、通知组件已加载完成,先调用子组件的这个函数,再调用父组件的这个函数,只调用一次,可以和 JS 其他框架交互了,
componentDidMount(){
    this.getAddressData()
}

@3、运行更新阶段:用户操作或父组件更新时进行界面调整

// 一、当组件接收到新的props的时候触发该函数,不会触发render()调用
// 参数:nextProps为即将被设置的属性
componentWillReceiveProps(nextProps){
    if (!this.state.autoPlay) {
           this.getAddressData()
    }
    this.setState({
        msg: 'props改变了'
    })
}

// 二、决定是否更新组件,返回bool,若为true,则更新组件,若返回false,则进入等待阶段。默认情况下,这个函数永远返回 true 用来保证数据变化的时候 UI 能够同步更新。
// 参数nextProps组件将更新的属性值,nextState组件即将更新的状态值
ShouldComponentUpdate(nextProps, nextState){
    return true;
}

// 三、预备更新组件:界面更新之前可以处理某些业务,不能使用this.setState更新状态。这个函数调用后nextProps,nextState就会分别设置到this.props和this.state中
componentWillUpdate(nextProps, nextState){

}

// 四、调用render(),根据diff算法,渲染界面,生成需要更新的虚拟Dom数据
render(){
    return(
        <View></View>
    )
}

// 五、虚拟Dom同步到Dom中后,可以做dom操作
// 除了首次render()调用的是componentDidMount函数,其他render()后都是调用componentDidUpdate函数
componentDidUpdate(){

}
//componentWillMount、componentDidMount和componentWillUpdate、componentDidUpdate可以对应起来。区别在于,前者只有在挂载的时候会被调用;而后者在以后的每次更新渲染之后都会被调用。
//ps:绝对不要在componentWillUpdate和componentDidUpdate中调用this.setState方法,否则将导致无限循环调用。

@4、卸载阶段

// 组件从Dom中移除,解除对应绑定的事件、清除定时器、移除虚拟Dom中对应的组件数据结构、取消网络请求等
componentWillUnmount(){

}

组件的生命周期

@补充信息–来源参考其他作者

触发组件更新的四种情况
1、首次加载的时候会触发更新
2、this.setState状态发生改变时更新
3、父组件的props属性发生改变时更新
4、this.forceUndate强制更新
触发组件更新的四种情况

猜你喜欢

转载自blog.csdn.net/snow51/article/details/80508234