生命周期的含义:是指某一个时刻组件会自动调用执行的函数
React生命周期分为4个大项
一、数据初始化
当创建页面时先调用的就是construction这个构造函数 在这个函数中props或state的变量将初始化。但construction是es6中的语法所以它不能当做react的生命周期函数
constructor(props) {
super(props);
this.state = {
inputValue: '',
list: ['11', '222']
};
}
二、 挂载页面
挂载页面时、将经历三个过程 挂载前 挂载 挂载后
//在组件即将第一次被挂载到页面时被调用
componentWillMount(){
console.log(componentWillMount);
}
//页面被挂载 创建虚拟dom,进行diff算法,更新dom树都在此进行
render(){
return()
}
//在组件第一次被挂载后被执行
componentDidMount(){
console.log(componentDidMount);
}
三、更新
当更新时必须要经历四个阶段 是否要更新 更新前 渲染dom 更新后,当组件为子组件时在接受父组件传参改变时要先经历props变更。
//当一个组件要从父组件接受参数
//只要父组件的render函数被‘重新’执行了 子组件将会调用这个函数(组件第一次渲染在父组件中不会
被执行)
componentWillReceiveProps(nextProps){
console.log(componentWillReceiveProps);
}
//在组件更新前,他会被执行 且返回一个对象ture或flase 判断是否需要更新组件
shouldComponentUpdate(nextProps, nextState){
console.log(shouldComponentUpdate);
return true
}
//只有在组件将要更新时才调用,此时可以修改state
componentWillUpdata(nextProps, nextState){
console.log(componentWillUpdata);
}
//渲染dom
render(){}
//组件更新完成后调用,此时可以获取dom节点
componentDidUpdate(){
console.log(componentDidUpdate);
}
四、卸载
//组件将要卸载时调用,一些事件监听和定时器需要在此时清除。
componentWillUnmount(){
}