- getDefaultProps 获取属性的默认值和校验传递属性的类型
- constructor getInitialState 在执行getInitialState之前,如果当前类组件有构造函数,则先执行该构造函数,从而初始化状态,把属性等信息挂载到实例上
- componentWillMount 第一次渲染之前,可以在这里提前从服务器获取数据,进而把获取的数据重赋值给状态或者存放到redux中。
- render渲染组件
- componentDidMount() 第一次组件渲染完成,然后处于运行当中。可以获取DOM元素了。
【state改变】
- shouldComponentUpdate 状态改变触发该钩子函数,此处可以判断该更新是否有必要,避免不必要的更新,从而得到优化,返回true或者false来控制是否执行下一个钩子函数,但是不论返回的哪个,状态都已经改了
- componentWillUpdate在上一个钩子函数返回true执行,做一系列的更新前准备
- render再次渲染,渲染状态改变的部分
- componentDidUpdate状态更新完成后,到再次监听属性或者状态的改变。
【props改变】
- componentWillReceiveProps属性值改变触发该钩子函数,获取到某一个具体属性的改变,然后触发shouldComponentUpdate,看看到底是否可以更新。
【卸载】
- componentWillUnmount 组件卸载之前,做最后一步的收尾工作,然后组件的整个生命周期结束。
代码示意以及各个周期函数的参数
class Clock extends React.Component {
static defaultProps = {
time:"1970年1月1日 0点0分0秒"
}
static propTypes = {
time:"instanceOf(Date)"
}
constructor(props){
super(props);
this.state = {t:0}
}
componentWillMount(){
console.log("--- 执行componentWillMount---")
}
render(){
console.log("--- 执行render---")
return <div>
<h2>回溯到{this.state.time}</h2>
<button Onclick={()=>{
this.setState({t:this.state.t+1})
}}>{this.state.t}</button>
</div>
}
componentDidMount(){
console.log("--- 执行componentDidMount---")
}
shouldComponentUpdate (nextProps,nextState) {
console.log("--- 执行shouldComponentUpdate ---",nextProps,nextState)
}
componentWillUpdate(){
console.log("--- 执行componentWillUpdate---")
}
//render重新渲染
componentDidUpdate(){
console.log("--- 执行componentDidUpdate---")
}
componentWillUnmount(){
console.log("--- 执行componentWillUnmount---")
}
}
React.render(<section>
<Clock></Clock>
</section>,document.getElementById("root"),_=>{alert("奥利给")})