一、react生命周期函数
- 组件将要挂载时触发的函数:componentWillMount
- 组件挂载完成时触发的函数:componentDidMount
- 是否要更新数据时触发的函数:shouldComponentUpdate
- 将要更新数据时触发的函数:componentWillUpdate
- 数据更新完成时触发的函数:componentDidUpdate
- 组件将要销毁时触发的函数:componentWillUnmount
- 父组件中改变了props传值时触发的函数:componentWillReceiveProps
1.初始化阶段:有ReactDOM.render()触发--初次渲染
- constructor()
- componentWillMount()
- render()
- componentDidMount()
2.更新阶段:由组件内部this.setState()或父组件重新render触发
- shouldComponentUpdate()
- componentWillUpdate()
- render()
- componentDidUpdate()
3.卸载阶段:由ReactDOM.unmountComponentAtNode()触发
- componentWillUnmount
二、生命周期执行流程
1.初始化阶段
1.首先会在static defaultProps={} 加载静态资源、默认的属性, 在通过static propTypes进行校验。2.然后在constructor(props)={}里初始化 加载默认的属性。3.componentWillMount父组件将要被挂载。4.render()方法进行渲染 。5.componentDidMount()={}父组件挂载完成。
2.组件运行阶段
1.组件运行时state发生改变就会在shouldComponentUpdate(nextProps,nextState)={}判断组件是否要更新。return true就会到componentWillUpdate()={}组件将要更新,然后render()在次渲染。在执行componentDidUpdate(){}。组件更新完成。
在shouldComponentUpdate()里return true的话就会和数据进行比较,从而会再次执行render()渲染会有内存消耗。如果return fasle的话就不会比较,就没有内存消耗。所以shouldComponentUpdate()是一个性能优化点。
2.当父组件有子组件时会重新render(),然后判断props有没有改变然后再执行componentWillReceiveProps(newProps){}:父组件中改变了props传值时触发的函数。然后再到shouldComponentUpdate()这个步骤。
3. 销毁阶段
componentWillUnmount(){} 组件卸载完成
三、代码
重要
componentDidMount():当前方法中,发起ajax请求
shouldComponentUpdate(nextProps,nextState):性能的优化点
import React, { Component } from 'react'
class SubCount extends Component {
componentWillReceiveProps(newProps){
console.log('子组件将要接收新属性',newProps);
}
render() {
return (
<div>
</div>
)
}
}
export default class LifyCycle extends Component {
// 静态资源对象
static defaultProps = {
// 1.加载默认的属性
name:'小张同学',
age:18
}
constructor(props){
super(props);
console.log("1.初始化 加载默认的属性");
this.state = {
count:0
}
}
componentWillMount(){
console.log('2.父组件将要被挂载');
}
componentDidMount(){
// 当前方法中,发起ajax请求
console.log('4.父组件挂载完成');
}
shouldComponentUpdate(nextProps,nextState){
// 性能的优化点
console.log('5.组件是否要更新');
return true;
}
componentWillUpdate(){
console.log('7.组件将要更新');
}
componentDidUpdate(){
console.log('8.组件已经更新完成');
}
componentWillUnmount(){
console.log('组件卸载完成');
}
handleClick = () =>{
this.setState((prevState,prevProps) => ({
// prevState:之前的状态 prevProps:之前的属性
count:prevState.count+1
}),()=>{
// 是一个回调函数,在状态之后执行
console.log(this.state.count);
})
}
render() {
console.log('3.父组件render了');
return (
<div>
<h2>{this.state.count}</h2>
<button onClick={this.handleClick}>+1</button>
<SubCount count={this.state.count}></SubCount>
</div>
)
}
}