组件加载的时候触发的函数:
constructor, //01构造函数
componentWillMount, //02组件将要挂载
render //不属于生命周期函数,03数据渲染
componentDidMount //04组件挂载完成 (dom操作)
组件更新时触发的函数:
shouldComponentUpdate // 01是否更新数据 需要return true。
componentWillUpdate //02组件将要更新
render //03数据渲染
componentDidUpdate // 04组件更新完成
销毁时触发函数
componentWillUnmount // 组件销毁
在父组件里面变props是触发
componentWillReceiveProps
案例demo
import React,{Component} from 'react'
class Lifecycle extends Component {
constructor(props) {
super(props);
console.log('01构造函数');
this.state = {
msg:'我是!'
};
}
componentWillMount(){
console.log('02组件将要挂载')
}
componentDidMount(){
console.log('04组件挂载完成')
}
Uptada=()=>{
this.setState({
msg:'更新后的数据'
})
}
//更新数据触发的方法
// 需要返回true
shouldComponentUpdate(nextProps,nextState){
console.log('01是否更新数据')
console.log(nextProps); // 父子组件传递的数据
console.log(nextState) // 改变的数据
return true
}
//将要更新数据时触发
componentWillUpdate(){
console.log('02组件将要更新')
}
//组件更新完成
componentDidUpdate(){
console.log('04组件更新完成')
}
// 组件销毁的时候触发的生命周期函数。
componentWillUnmount(){
console.log('组件销毁了')
}
componentWillReceiveProps(){
}
render() {
console.log('03数据渲染')
return (
<div>
<h2>数据更新··{this.state.msg}</h2>
<button onClick={this.Uptada}>点击更新数据</button>
</div>
);
}
}
export default Lifecycle;
如果有问题,可以加我微信一起讨论,我们一起进步!
屏幕前的你,加油!