react生命周期-旧
示意图
组件各生命周期钩子
componentWillMount
:组件将要挂载时执行
componentDidMount
:组件已经挂载后执行,一般在这个钩子里做一些初始化的事,发送请求,设置定时器…,孩子出生
render
:只要组件变化就会触发的函数,孩子成长
componentWillReceiveProps
:组件将要父组件传来的属性时执行
shouldComponentUpdate
:判断是否需要组件更新
componentWillUpdate
:组件将要更新时执行
componentDidUpdate
:组件已经更新后执行
componentWillUnmount
:组件将要卸载时更新,一般在这个钩子中做一些收尾的事,例如:关闭定时器,取消订阅,孩子去世
初始化阶段生命周期
由ReactDOM.render()触发
constructor->componentWillMount->render->componentDidMount
更新时生命周期
三种情况:父组件render时、执行setState()方法时、执行forceUpdate()时
-
父组件render时:
componentWillReceiveProps->shouldComponentUpdate->componentWillUpdate->render->componentDidUpdate
-
执行setState()方法时:
shouldComponentUpdate->componentWillUpdate->render->cpmponentDidUpdate
-
执行forceUpdate()方法时:
componentWillUpdate->render->componentDidUpdate
react组件销毁时生命周期
componentWillUnmount
常用的钩子函数
render/componentDidMount/componentWillUnmount
react生命周期-新
新版本的react生命周期需要在17.0.1版及以上版本的React-ReactDOM-babel中才能使用
在新版本里面能用旧的钩子
示意图
react新版本生命周期对旧版本的更新
一、UNSAFE_
-
在18.x版本之后,以下几个钩子函数必须在前面加上UNSAFE前缀
UNSAFE_componentWillUpdate
UNSAFE_componentWillMount
UNSAFE_componentWillReceiveProps
-
除了componentWillUnMount,其他带Will的钩子函数都需要加UNSAFE_
-
为什么要加:React在异步渲染时用上面这些函数是不安全的,就是为了防止人们误解和滥用
二、新增钩子
-
getDerivedStateFromProps
:从属性中获取派生状态值,该函数执行,会返回一个对象,组件会以这个函数的返回值作为自己的state值- 派生:从父组件中获取到的
-
getSnapshotBeforeUpdate
:更新之前获取快照,保留更新之前的数据
新版本中的初始化阶段
constructor->getDerivedStateFromProps->render->compoentDidMount
新版本中的更新阶段
- New Props、setState():
getDerivedStateFromProps->shouldComponentUpdate->render->getSnapshotBeforeUpdate->componentDidUpdate
- forceUpdate():
getDerivedStateFromUpdate->render->getSnapshotBeforeUpdate->cmponentDidUpdate
新生命周期与旧生命周期钩子的区别
- 新增了两个生命周期钩子
- 废弃了三个生命周期钩子
getDerivedStateFromProps(props,state)
- 将派生的props值代替state
class Deom extends React.Component{
getDerivedStateFromProps(props,state){
return //state对象或null
}
render(){
return (
<h1></h1>
)
}
}
- 若state的值任何时候都取决于props,可以用这个
getSnapshopBeforeUpdate()
-
作用:获取到的快照通过return能够传给
-
例子:
-
class Demo extends React.Component{ getSnapshotBeforeUpdate(){ return "haha" } componentDidUpdate(prep,pres,snap){ console.log(snap)//“haha” } }
-
componentDidUpdate(preProps,preState,snapshotValue)
- 作用:组件更新之后调用的函数
- 参数:
- preProps:更新之前的props
- preState:更新之前的状态
- snapshotValue:执行快照函数返回的值
总结:
初始化阶段:
- constructor()
- getDerivedStateFromProps()
- render()
- componentDidMount()
更新阶段:
- getDerivedSateFromProps()
- shouldComponentUpdate()
- render()
- getSnapshotBeforeUpdate()
- componentDidUpdate()
卸载阶段:
- ComponentWillUnmount()
生命周期钩子总结
重要的钩子:
- render()
- componentDidMount()
- componentWillUnmount()
即将废弃的钩子:
- componentWillMount()
- componentWillUpdate()
- componentWillReceiveProps()