组件的生命周期: 类组件的生命周期
1、初始化(之后): constructor
1.1 shouldComponentUpdate
1.2 render
2、挂载(之后): componentDidMount(在组件初始化之后仅执行一次)
3、更新(之后): componenttDidUpdate (在组件挂载之后执行, 执行的次数 零到多次)
4、销毁(之前)componentWillUnmount
Father:
import { Component } from 'react';
import Son from './Son';
class Father extends Component {
constructor(props){
super(props);
this.state = {
msg: 'Hello 生命周期'
}
this.intervalID = undefined; //定时器ID
console.log('Father组件 调用构造函数constructor.......');
}
render() {
console.log('Father组件 调用render函数render.......');
return (
<div>
<h1>Father组件:</h1>
<button className='btn btn-primary' onClick={e=>this.handleMsg(e)}>更新</button>
<h2>{this.state.msg}</h2>
<hr/>
<Son/>
</div>
)
}
initTimer(){
this.intervalID = setInterval(() => {
console.log('定时器执行.........', new Date());
this.setState({
msg: new Date()+''
})
}, 1000);
}
handleMsg(e){
this.setState({
msg: '已修改 '+ new Date().getTime()
});
}
componentDidMount(){
console.log('Father组件 调用挂载函数componentDidMount.......');
this.initTimer();
}
componentDidUpdate(){
console.log('Father组件 调用更新函数componentDidUpdate.......');
}
componentWillUnmount(){
console.log('Father组件 调用销毁之前函数componentWillUnmount.......');
if(this.intervalID){
clearInterval(this.intervalID);
this.intervalID = undefined;
}
}
}
export default Father
父子组件生命周期:
1、Father Constructor
2、Father render
3、Son Constructor
4、Son render
5、Son compopnentDidMount
6、 Father componentDidMount
更新:
1、Father render
2、Son render
3、Son componentDidUpdate
4、Father componentDidUpdate
销毁之前
1、Father componentWillUnmount
2、 Son componentWillUnmount
销毁
1、Son 组件先销毁
2、Father 组件销毁
*/
Son:
import { Component } from 'react'
class Son extends Component {
constructor(props){
super(props);
this.state = {
msg: 'Hello Son生命周期'
}
console.log('Son 调用构造函数constructor.......');
}
render() {
console.log('Son 调用render函数render.......');
return (
<div>
<h1>Son组件:</h1>
<button className='btn btn-primary' onClick={e=>this.handleMsg(e)}>更新</button>
<h2>{this.state.msg}</h2>
</div>
)
}
handleMsg(e){
this.setState({
msg: 'Son已修改 '+ new Date().getTime()
});
}
componentDidMount(){
console.log('Son 调用挂载函数componentDidMount.......');
}
componentDidUpdate(){
console.log('Son 调用更新函数componentDidUpdate.......');
}
componentWillUnmount(){
console.log('Son 调用销毁之前函数componentWillUnmount.......');
}
}
export default Son;