react组件生命周期:老版本和新版本不一样
老版本即将丢弃的三个生命周期:混淆异步勾子
componentWillMount
componentWillReceiveProps
componentWillUpdate
import React, { Component } from 'react';
class demo extends Component {
//老版本的一些生命周期
//1. 初始化阶段: 由ReactDOM.render()触发---初次渲染
// 1. constructor()
// 2. componentWillMount()
// 3. render()
// 4. componentDidMount() =====> 常用
// 一般在这个钩子中做一些初始化的事,例如:开启定时器、发送网络请求、订阅消息
//2. 更新阶段: 由组件内部this.setSate()或父组件render触发
// 1. shouldComponentUpdate()
// 2. componentWillUpdate()
// 3. render() =====> 必须使用的一个
// 4. componentDidUpdate()
//3. 卸载组件: 由ReactDOM.unmountComponentAtNode()触发
// 1. componentWillUnmount() =====> 常用
// 一般在这个钩子中做一些收尾的事,例如:关闭定时器、取消订阅消息
//新版本的一些生命周期写法
//1. 初始化阶段: 由ReactDOM.render()触发---初次渲染
// 1. constructor()
// 2. getDerivedStateFromProps
// 3. render()
// 4. componentDidMount() =====> 常用
// 一般在这个钩子中做一些初始化的事,例如:开启定时器、发送网络请求、订阅消息
//2. 更新阶段: 由组件内部this.setSate()或父组件重新render触发
// 1. getDerivedStateFromProps
// 2. shouldComponentUpdate()
// 3. render()
// 4. getSnapshotBeforeUpdate
// 5. componentDidUpdate()
//3. 卸载组件: 由ReactDOM.unmountComponentAtNode()触发
// 1. componentWillUnmount() =====> 常用
// 一般在这个钩子中做一些收尾的事,例如:关闭定时器、取消订阅消息
// 使用:
componentWillMount(){
console.log('componentWillMount----组建将要挂载在页面的时刻')
}
componentDidMount(){
console.log('componentDidMount----组建挂载完成的时刻')
}
shouldComponentUpdate(nextProps,nextStates){//这个生命周期需要返回一个布尔值,true:继续往下执行,false:不往下执行
console.log('1-shouldComponentUpdate');
// if(nextProps.content !== nextState.content){//要用双等于号
// return true;
// }else{
// return false;
// }
return true;
}
componentWillUpdate(){
console.log('2-componentWillUpdate')
}
componentDidUpdate(){
console.log("4-组建更新完成之后执行")
}
//1.放在子组建中,2.组建第一次存在于dom中,函数是不会被执行的,3.已经存在于dom中,函数才会执行
componentWillReceiveProps(){
console.log("child-componentWillReceiveProps-")
}
componentWillUnmount(){
console.log("组建将要被删除之前执行")
}
render() {
console.log('3-render---组建挂载中')
return (
<div></div>
);
}
}
export default demo;