React从0到1--组件生命周期

1、React 严格定义了组件的生命周期,生命周期可能会经历如下三个过程
装载过程( Mount),也就是把组件第一次在 DOM 树中渲染的过程;
更新过程( Update ),当组件被重新渲染的过程;
卸载过程( Unmount),组件从 DOM 中删除的过程

2、装载过程

我们先来看装载过程,当组件第一次被渲染的时候,依次调用的函数是如下这些:
constructor
getlnitialState
getDefaultProps
componentWillMount
render
componentDidMount

1. constructor
  
Es6中创建一个组件的实例,无状态的React组件不需要实例

1、初始化state

this.state = {
count: props.initValue || 0
}

2、绑定成员的this环境

this.onClickIncButton = this.onClickIncButton.bind(this);
this.onClickDecButton = this.onClickDecButton.bind(this);

3、getlnitialState 和 getDefaultProps
React.createClass 方法创造的组件类才会用到这两种方法,分别用来初始化state和props

4、render
用于渲染DOM的函数,非常重要


5、componentWillMount 和 componentDidMount

//组件装载前
componentWillMount() {
console.log ('enter componentWillMount'+ this.props.caption);

}
//组件装载后,DOM已经存在,可以使用其他的库,比如JQ来执行其他操作
componentDidMount() {
console.log ('enter componentWillMount'+ this.props.caption);

}

6、shouldComponentUpdate(nextProps, nextState)
shouldComponentUpdate决定了一个组件什么时候不需要渲染,必须有返回值,true是渲染,false是不渲染

shouldComponentUpdate(nextProps, nextState){
console.log(nextProps, nextState)

console.log(this.state)
return (nextProps.caption!==this.props.caption)||(nextState.count!==this.state.count)


}
7、componentWillUnmount 
用于卸载组件










 

 



posted @ 2018-10-17 13:55  码我滴码  阅读(179)  评论(0编辑  收藏  举报