原文:How to use React Lifecycle Methodsjavascript
大致上分三类java
componentWillMount()
复制代码
当 React 渲染一个组件的是你,首先进入该方法。react
Note:componentWillMount()
是惟一一个在render()
以前调用的生命周期方法。所以是在服务端渲染中惟一被调用的方法。网络
由于componentWillMount()
将被删除,因此官方推荐使用constructor()
替代该方法fetch
**Update:**该方法应该在新的代码中避免使用动画
能够在该方法中使用this.setState()
可是不必定触发从新渲染。this
componentDidMount()
复制代码
当该方法被调用时候,React 已经渲染了组件而且将组件插入 DOM。所以若有有任何依赖于 DOM 的初始化,应该放在这里。spa
该方法中可使用this.setState()
方法,它将触发从新渲染。code
componentWillReceiveProps(nextProps)
复制代码
当组件接收到新的props
,该方法会首先被调用,可是须要注意一点,即便props
并无发生改变,该方法也会被调用,因此使用该方法的时候要确保比较this.props
和nextProps
,避免没必要要的渲染。component
Update:componentWillReceiveProps
将被移除,使用新的static getDerivedStateFromProps
代替。
static getDerivedStateFromProps(props, state)
复制代码
每次render
都会调用该方法——即便props
没有发生变化。因此要谨慎使用。
shouldComponentUpdate(nextState, nextProps)
复制代码
有些时候须要避免没必要要的渲染,可使用该方法。返回false
意味着 React 不执行componentWillUpdate()
,render()
,componentDidUpdate()
。
该方法在初始化时候不执行。
**Note:**根据 React 文档,React 可能将shouldComponentUpdate
视作提示而不是严格的根据它的返回结果决定是否执行,也就是说可能出现shouldComponentUpdate
返回false
,可是仍是发生从新渲染。
在该方法中不能够设置setState
。
如前所述,该方法可能有有问题。React 官方提供了另外一个解决办法,因此若是发现某个组件慢,可使用React.PureComponent
替代React.component
,它将对props
和state
提供一个浅层对照。
componentWillUpdate(nextProps, nextState)
复制代码
该方法在被渲染前调用。shouldComponentUpdate
在新的props
进入组件或者state
改变的时候调用。
该方法在初始渲染时候不被调用。
Update:shouldComponentUpdate
即将被移除。
在该方法中不能调用setState
。
shouldComponentUpdate
方法在render()
前会被准确调用,因此在该方法中作任何跟 DOM 相关的操做是不合适的,由于很快会过时。
常见的用例有:
state
的变化设置变量getSnapshotBeforeUpdate(prevProps, prevState)
复制代码
该方法在 React 16.3 被添加而且它配合componentDidUpdate
。该方法应该覆盖了旧方法shouldComponentUpdate
的全部用例。
getSnapshotBeforeUpdate
在元素被渲染并写入 DOM 以前调用,这样,你在 DOM 更新前捕获 DOM 信息(例如:滚动位置)。
应该返回一个snapshot
值或null
,不管返回什么,shouldComponentUpdate
均可以接收到snapshot
参数。
若是想要得到一个 list 或者一个聊天窗口中的滚动位置,能够在getSnapshotBeforeUpdate
中取到这些信息。而后将滚动信息做为snapshot
值返回。这容许在更新DOM后在componentDidUpdate
中设置正确的滚动位置。
componentDidUpdate(prevProps, prevState, snapshot)
复制代码
React 更新组件后,调用componentDidUpdate
。该方法在初始渲染时候不会被调用。
若是组件更新后须要操做 DOM,可使用该方法。
componentWillUnmount()
复制代码
在卸载,销毁组件以前调用该方法。
在卸载组件时候不能设置 State
使用该方法清理 actions。
componentDidMount
或其余地方添加的事件监听componentDidMount
中建立的 DOM 元素