React的生命周期
在React 15.x版本或者之前的版本,生命周期只有三个阶段
在React 16.3之后新增了一个;有12个钩子函数,四个阶段分别为:初始化,运行中,销毁,错误处理
组件从创建到销毁的过程被称为组件的生命周期,通常分为三个阶段:挂载阶段,更新阶段,卸载阶段
Mounting: constructor -> render -> (React updates dom and refs) -> componentDidMount
Updating: (newProps setState() forceUpdate()) -> componentDidUpdate
Unmounting: componentWillUnMount
一、挂载阶段
-
constructor,初始化state和绑定事件处理方法
-
componentWillMount,组件即将挂载,只调用一次(已废弃)
-
render,定义组件,是一个纯函数:
1.计算this.props/this.state返回的对应结果
2.通过React.createElement将jsx转换为VDOM对象模型 -
componentDidMount,在组件被挂载到Dom后调用,只调用一次,这个时候已经可以获取到dom结构
二、更新阶段
- componentWillReceviesProps(nextProps),只会在props引起的组件更新时候调用(已废除)
- shouldComponentUpdate(nextProps,nextState),通过返回true跟false来决定组件是否更新,在这里不能调用setState,会引起循环调用
- componentWillUpdate(nextProps,nextState),组件更新前,在这里不能调用setState,会引起循环调用(已废除)
- componentDidUpate(prevProps,prevState)
三、卸载阶段
- componentWillUnmount
四、错误处理阶段
- componentDidCatch(err,info)
新的生命周期废除了原来的 componentWillMount componentWillReceviesProps componentWillUpdate,新增了static getDerivedStateFromProps getSnapshotBeforeUpdate
旧的生命周期:
初始化;
Mounting:componentWillMount render componentDidMount
Updating:
props 更新: componentReceiveProps shouldComponentUpdate
如果 shouldComponent 返回true, componentWillUpdate render componentDidUpdate
state 更新: shouldComponentUpdate
如果 shouldComponentUpdate 返回true, componentWillUpdate render componentDidUpdate
Unmounting:componentWillUnmount;
新的生命周期:
Mounting:constructor getDerivedStateFromProps render componentDidMount
Updating:
props 更新: getDerivedStateFromProps shouldComponentUpdate
如果 shouldComponent 返回true, render getSnapshotBeforeUpdate componentDidUpdate
state 更新: shouldComponentUpdate
如果 shouldComponentUpdate 返回true, render getSnapshotBeforeUpdate componentDidUpdate
force update: render getSnapshotBeforeUdate componentDidUpdate
Unmounting: componentWillMount
被废弃的三个函数都是在render之前,因为fiber的出现,很可能因为高优先级任务的出现打断现有任务导致它们被执行多次
-
1) componentWillMount,可用constructor+componentDidMount代替
-
2) componentWillReceviesProps,会破坏state数据的单一数据源,导致组件状态不好预测,还会增加重绘次数,用getDerivedStateFromProps替代
-
3) getDerivedStateFromProps(nextProps,prevState);
componentWillReceviesProps(nextProps){
if(nextProps.xxx!==this.props.xxx){
this.setState({
xxx: nextProps.xxx
})
};
this.xxx();
}
对比
static getDerivedStateFromProps(nextProps,prevState){
if(nextProps.xxx!==prevState.xxx){
return {
xxx : nextProps.xxx
}
}
}
componentDidUpdate(prevProps,prevState){
this.xxx()
}
-
- componentWillUpdate,用getSnapshotBeforeUpdate(prevProps,prevState)返回的值作为componentDidUpdate第三个参数;componentDidUpdate(prevProps,prevState,snap)
-
- getSnapshotBeforeUpdate会在最终确定的render执行之前执行,能保证到跟componentDidUpdate的元素状态相同