前言
react生命周期在16.3之后有所变化,增加了一些函数,这里还是用16.3之前的内容
三个阶段生命周期
- 创建阶段
- 更新阶段
- 卸载阶段
生命周期钩子函数
以下生命周期钩子函数按序号顺序执行
创建阶段
- Constructor(props、state)
- componentWillMount
- render
- componentDidMount
其中Constructor为初始化阶段,其他三个为挂载阶段
Constructor
一个类必须有一个Constructor方法,如果Constructor没有被定义,一个默认的Constructor会被添加,一个Constructor会返回实力对象,有了实例对象之后就可以使用this关键字
- 初始化内部状态,显性设置和隐性设置
- 需要使用super(调用基类的构造方法)
- 可以直接修改state
componentWillMount
需要使用此方法的内容基本都可以写在Constructor中,所以此方法很少用
- UI渲染完成前调用
- 只执行一次
- 这里调用setState不会触发render
render
- 一个组件必须有的方法
- 返回一个顶级的react元素
- 渲染的是dom tree的一个react对象
react之所以效率高就是因为使用了虚拟的dom tree
注意:不能在render方法里执行this.setState()
componentDidMount
适合用来请求后端数据
- UI渲染完成后调用
- 只执行一次
- 获取一些外部数据资源
更新阶段
- componentWillRecieveProps
- shouldComponentUpdate
- render
- componentDidUpdate
组件的props或者state发生变化时,组件会做出相应的更新
componentWillRecieveProps
- 组件接收到新的props的时候会触发
- 在此对比新的props和原来的props
- 不推荐使用,因为之后的版本会有新的函数会取代它
shouldComponentUpdate
- 是否要继续执行render方法
- 可以由PureComponent自动实现
componentDidUpdate
- 每次UI更新时调用
- 更新一些外部数据资源
卸载阶段
- componentWillUnmount
componentWillUnmount
- 组件移除时候调用
- 可以用来做资源的释放