React v16.0前的生命周期
React 生命周期分为三种状态
初始化
更新
销毁
**•初始化 **
**1、getDefaultProps() **
设置默认的props,也可以用dufaultProps设置组件的默认属性.
**2、getInitialState() **
在使用es6的class语法时是没有这个钩子函数的,可以直接在constructor中定义this.state。此时可以访问this.props
**3、componentWillMount() **
组件初始化时只调用,以后组件更新不调用,整个生命周期只调用一次,此时可以修改state。因为render前,所以setState不会重新渲染,推荐用constructor代替之
4、 render()
react最重要的步骤,创建虚拟dom,进行diff算法,更新dom树都在此进行。此时就不能更改state了。
5、componentDidMount()
组件渲染之后调用,只调用一次。
•更新
6、componentWillReceiveProps(nextProps)
组件初始化时不调用,组件接受新的props时调用。
**7、shouldComponentUpdate(nextProps, nextState) **
在接收到新的props或state时是否重新渲染,默认返回true,此方法通过比较nextProps,nextState及当前组件的this.props,this.state,返回true时当前组件将继续执行更新过程,返回false则当前组件更新停止,以此可用来减少组件的不必要渲染,优化组件性能。
8、componentWillUpdata(nextProps, nextState)
此方法在调用render方法前执行,在这边可执行一些组件更新发生前的工作,一般较少用。
9、render()
组件渲染
10、componentDidUpdate()
此方法在组件更新后被调用,可以操作组件更新的DOM,prevProps和prevState这两个参数指的是组件更新前的props和state
•卸载
11、componentWillUnmount()
此方法在组件被卸载前调用,可以在这里执行一些清理工作,比如清楚组件中使用的定时器,清楚componentDidMount中手动创建的DOM元素等,以避免引起内存泄漏
React v16.4 的生命周期
变更缘由 原来(React v16.0前)的生命周期在React v16推出的Fiber之后就不合适了,因为如果要开启async rendering,在render函数之前的所有函数,都有可能被执行多次。
**•static getDerivedStateFromProps **
在组件创建时和更新时的render方法之前调用,它应该返回一个对象来更新状态,或者返回null来不更新任何内容。,用于替换componentWillMount,componentWillReceiveProps,componentWillUpdate
•getSnapshotBeforeUpdate
用于替换 componentWillUpdate, 该函数会在update后 DOM 更新前被调用,用于读取最新的 DOM 数据,返回值将作为 componentDidUpdate 的第三个参数
官网部分代码示例
推荐使用:
class A extends React.Component {
// 用于初始化 state
constructor() {}
// 用于替换 componentWillReceiveProps
,该函数会在初始化和 update
时被调用
// 因为该函数是静态函数,所以取不到 this
static getDerivedStateFromProps(nextProps, prevState) {}
// 判断是否需要更新组件,多用于组件性能优化
shouldComponentUpdate(nextProps, nextState) {}
// 组件挂载后调用
// 可以在该函数中进行请求或者订阅
componentDidMount() {}
// 用于获得最新的 DOM 数据
getSnapshotBeforeUpdate() {}
// 组件即将销毁
// 可以在此处移除订阅,定时器等等
componentWillUnmount() {}
// 组件销毁后调用
componentDidUnMount() {}
// 组件更新后调用
componentDidUpdate() {}
// 渲染组件函数
render() {}
// 以下函数不建议使用
UNSAFE_componentWillMount() {}
UNSAFE_componentWillUpdate(nextProps, nextState) {}
UNSAFE_componentWillReceiveProps(nextProps) {}
}