React组件的生命周期根据定义描述,可以分为挂载,渲染和渲染这几个阶段。当渲染后的组件需要更新时,我们会重新去渲染组件,直至卸载。
1.组件的挂载
这个过程主要做组件状态的初始化
import React, {Component, PropTypes} from 'React';
class App extends Component {
static propTypes = {
};
static defaultProps = {
};
constructor(props) {
super(props);
this.state = {
};
}
componnetWillMount() {
}
componentDidMount() {
}
render() {
return <div>This is a demo.</div>;
}
};
propTypes提供类型检查,defaultProps指明默认类型。
componentWillMount方法在render方法之前执行,而componentDidMount()在render方法之后执行。
上面的方法都只会在组件初始化时执行一次。
但如果我们在componentDidMount中执行setState方法,则在初始化过程中我们就渲染了两次
2.组件的卸载
组件的卸载非常简单,只有componentWillUnmount这一个卸载前状态
import React, { Component, PropTypes } from 'React';
class App extends Component {
componentWillUnmount() {
}
render() {
return <div>This is a demo.</div>;
}
}
在componentWillUnmount方法中,我们常常会执行一些清理方法,如事件回收或是清楚定时器。
3.数据更新过程
更新过程指的是父组件向下传递props或组件自身执行setState方法时发生的一系列更新动作
import React, { Component, propTypes } from 'React';
class App extends Component {
componentWillReceiveProps(nextProps){
}
shouldComponentUpdate(nextProps, nextState){
}
componentWillUpdate(nextprops, nextState) {
}
componentDidUpdate(nextProps,nextState) {
}
render() {
return <div>This is a demo.</div>;
}
}
如果组件自身的state更新了,那么会一次执行shouldComponentUpdate,componentWillUpdate,render和componentDidUpdate
shouldComponentUpdate是一个特别的方法,它需要接受更新的props和state,让开发者进行必要的条件判断,让其在需要时更新,不需要时不更新。因此,当方法返回false的时候,组件不再向下执行生命周期方法。shouldComponentUpdate是用来正确的对组件进行渲染,当父节点的props改变的时候,我们只需要在组件树上修改一条路径即可,而不需要重新渲染整棵组件书。而给我们指明路径的就是shouldComponentUpdate返回的值,所以这个方法也是性能优化的手段之一。
componentWillUpdate和componentDidUpdate分别提供需要更新的props和state以及更新之前的props和state。
如果组件是由父组件更新props而更新的,那么在shouldComponentUpdate之前会执行componentWillReceiveProps方法。此方法可以作为React在props传入之后,渲染之前setState的机会。在此方法中调用setState是不会二次渲染的
整个React生命周期就是分为大的三个环节,挂载,更新,卸载。
图中也表明了可以使用setState的方法,中间的实心节点代表已挂载的节点,可以强制更新forceUpdate(),也可以通过ShouldComponentUpdate的值来判断是否更新。