react生命周期的一些更新
React V16.3 新增的生命周期方法
getDerivedStateFromProps()
getSnapshotBeforeUpdate()
逐渐废弃的生命周期方法:
componentWillMount()
componentWillReceiveProps()
componentWillUpdate()
虽然废弃了这三个生命周期方法,但是为了向下兼容,将会做渐进式调整。
V16.3 并未删除这三个生命周期,同时还为它们新增以 UNSAFE_ 前缀为别名的三个函数 UNSAFE_componentWillMount()、UNSAFE_componentWillReceiveProps()、UNSAFE_componentWillUpdate()。
在 16.4 版本给出警告将会弃用 componentWillMount()、componentWillReceiveProps()、componentWillUpdate() 三个函数
然后在 17 版本将会删除 componentWillMount()、componentWillReceiveProps()、componentWillUpdate() 这三个函数,会保留使用 UNSAFE_componentWillMount()、UNSAFE_componentWillReceiveProps()、UNSAFE_componentWillUpdate()
生命周期简介
React组件的生命周期实际是提供给React用于将React元素构建渲染挂载到真实的Dom节点的各个时期的钩子函数。各个生命周期函数提供,使得在开发组件时可以控制各个时期执行不同的操作,如异步的获取数据等。
生命周期的预览
React组件的生命周期根据广义定义描述,可以分为挂载、渲染和卸载这几个阶段,当渲染后的组件需要更新时,我们会重新去渲染组件,直至卸载。
组件的挂载阶段
组件首次被实例化创建并插入DOM中需要执行的生命周期函数:
constructor(): 需要在组件内初始化state或进行方法绑定时,需要定义constructor()函数。不可在constructor()函数中调用setState()。
static getDerivedStateFromProps(): 执行getDerivedStateFromProps函数返回我们要的更新的state,React会根据函数的返回值拿到新的属性。
render(): 函数类组件必须定义的render()函数,是类组件中唯一必须实现的方法。render()函数应为纯函数,也就是说只要组件state和props没有变化,返回的结果是相同的。其返回结果可以是:1、React元素;2、数组或 fragments;3、Portals;4、字符串或数值类型;5、布尔值或null。不可在render()函数中调用setState()。
componentDidMount(): 组件被挂载插入到Dom中调用此方法,可以在此方法内执行副作用操作,如获取数据,更新state等操作。
组件的卸载阶段
组件的卸载比较简单,只有componentWillUnmount这个生命周期函数可供使用,在componentWillUnmount方法中,我们常常会执行一些清理方法,如时间回收或是清除定时器。
组件的更新阶段
更新过程是指父组件向下传递props或者组件自身执行setState方法时发生的一系列更新动作
旧的方法
import React, {Component, PropTypes} from 'react';
class App extends Component{
componentWillReceiveProps(nextProps){
// ...
}
shouldComponentUpdate(nextProps,nextState){
// ...
}
componentWillUpdate(nextProps,nextState){
// ...
}
componentDidUpdate(preProps,prevState){
// ...
}
render(){
return <div>This is a demo</div>
}
}
如果组件自身的state更新了,那么会依次执行shouldComponentUpdate、componentWillUpdate、render和componentDidUpdate
react-v16.3+后的新方法
当组件的props或state改变时会触发更新需要执行的生命周期函数:
static getDerivedStateFromProps(): getDerivedStateFromProps会在调用 render方法之前调用,并且在初始挂载及后续更新时都会被调用。它应返回一个对象来更新state,如果返回null则不更新任何内容。
shouldComponentUpdate(): 是一个特别的方法,它接受需要更新的props和state,让开发者增加必要的条件判断,让其在需要时更新,不需要时不更新。因此,当方法返回false的时候,组件不再向下执行生命周期方法。shouldComponentUpdate的本质是用来进行正确的组件渲染。
React.PureComponent 就是基于浅比较进行性能优化的。一般在实际组件实践中,不建议使用该方法阻断更新过程,如果有需要建议使用React.PureComponent。
render(): 在组件更新阶段时如果shouldComponentUpdate()返回false值时,将不执行render()函数。
getSnapshotBeforeUpdate(): 该生命周期函数执行在pre-commit阶段,此时已经可以拿到Dom节点数据了,该声明周期返回的数据将作为componentDidUpdate()第三个参数进行使用。
componentDidUpdate(): shouldComponentUpdate()返回值false时,则不会调用componentDidUpdate(),componentDidUpdate提供更新前的props和state