React的生命周期
1 生命周期图示
- 旧版生命周期
- 新版生命周期
2 生命周期的三个阶段
- 创建阶段(挂载时)
- 更新阶段
- 卸载阶段
3 生命周期执行顺序
3.1 创建阶段
- constructor
- 触发时机:创建组件,初始化
- render
- 触发时机:组件渲染完毕(禁止在render中调用this.setState,会发生递归报错)
- componentDidMount
- 触发时机:组件挂载后(DOM渲染完毕)
- 作用:
- 发送Ajax网络请求
- DOM操作
3.2 更新阶段
三种导致组件更新的情况:组件接收到新属性、更新原属性、forceUpdate()(强制更新)
- render
- 触发时机:组件渲染完毕
- componentDidUpdate
- 触发时机:组件完成更新后
- 作用:
- 发送Ajax网络请求
- DOM操作(若有setState必须放在if条件中)
3.3 卸载阶段
- componentWillUnmount
- 触发时机:组件将要卸载
- componentDidUpdate
- 触发时机:组件完成更新后
- 作用:
- 发送Ajax网络请求
- DOM操作(若有setState必须放在if条件中)
3.4 新生命周期函数执行顺序
-
constructor — 构造函数
-
getDerivedStateFromProps — 从props中获取state(静态方法)
-
render — 渲染页面
-
componentDidMount — 组件已挂载(DOM渲染完毕)
在更新数据后
-
getDerivedStateFromProps — 从props中获取state(静态方法)
-
shouldComponentUpdate — 手动地判断是否进行组件更新
-
render — 渲染页面
-
getSnapshotBeforeUpdate — 更新之前获取快照
-
componentWillUnmount — 将要卸载[不常用]
-
componentDidUpdate — 完成更新
示例Demo
import React from 'react';
import ReactDOM from 'react-dom';
class Person extends React.Component {
// 创建组件初始化
constructor(props) {
super(props)
this.state = {
count: 0
}
console.log('构造函数执行');
}
// 组件挂载后(DOM渲染完毕)
componentDidMount() {
console.log('生命周期钩子函数:--- componentDidMount === 组件已挂载(DOM渲染完毕)');
}
// 从props中获取state
static getDerivedStateFromProps() {
console.log('静态生命周期钩子函数:--- getDerivedStateFromProps === 从props中获取state');
return true
}
// 根据条件,决定是否当前渲染组件
shouldComponentUpdate(nextProps,nextState) {
console.log('生命周期钩子函数:--- shouldComponentUpdate === 组件应该更新');
console.log('最新的Props:',nextProps)
console.log('最新的state:',nextState)
return true
/*
必须有布尔类型返回值
若为true,则会更新数据;
若为false,则不会去更新数据
*/
}
// 更新之前获取快照
getSnapshotBeforeUpdate() {
console.log('生命周期钩子函数:--- getSnapshotBeforeUpdate === 更新之前获取快照');
return true
/*
必须有布尔类型返回值
*/
}
// 组件完成更新
componentDidUpdate() {
console.log('生命周期钩子函数:--- componentDidUpdate === 完成更新');
}
// 渲染页面
render() {
console.log('render提交执行---渲染页面');
return (
<div>
{this.state.count >= 3 ?
(<font color="red">数字大于等于3了</font>) :
(<Son fatherCount={this.state.count}></Son>)}
<div>
<button onClick={() => { this.setState({ count: this.state.count + 1 }) }}>+</button>
</div>
</div>
)
}
}
class Son extends React.Component {
// 将要卸载
componentWillUnmount() {
console.log('生命周期钩子函数:--- componentWillUnmount === 将要卸载');
}
render() {
return (
<div>
<p>数量:{this.props.fatherCount}</p>
</div >
)
}
}
ReactDOM.render(<Person></Person>, document.getElementById('root'))