组件初始化 Mounting
组件运行时 Updating
组件卸载时 Unmounting
react的生命周期在16版前后有更改
www.jianshu.com/p/514fe21b9…
父子组件加载和更新顺序和vue差不多,都是父组件先进入子组件完成后才会挂载完成父组件
mountComponent负责管理生命周期中的mounting阶段的方法调用
mountComponent本质上是通过递归渲染内容的,由于递归的特性,父组件的componentWillMount在其子组件的componentWillMount之前调用,而父组件的componentDidMount在其子组件的componentDidMount之后调用
updateComponent负责管理生命周期中的updating阶段的方法调用
updateComponent本质上是通过递归渲染内容的,由于递归的特性,父组件的componentWillUpdate在其子组件的componentWillUpdate之前调用,而父组件的componentDidUpdate在其子组件的componentDidUpdate之后调用
备注:
react生命周期:挂载,更新,错误处理 ,卸载
挂载:constructor()、static getDerivedStateFromProps()、render()、componentDidMount()
更新:static getDerivedStateFromProps()、shouldComponentUpdate()、render()、getSnapshotBeforeUpdate()、componentDidUpdate()
错误处理:static getDerivedStateFromError()、componentDidCatch()
卸载:componentWillUnmount()
react生命周期函数:
constructor():组件构造函数,在组件挂载之前调用;仅用于初始化内部state以及为事件处理函数绑定实例;
static getDerivedStateFromProps():会在调用 render 方法之前调用,并且在初始挂载及后续更新时都会被调用,此方法适用于state 的值在任何时候都取决于 props;
render():是 class 组件中唯一必须实现的方法;
componentDidMount:会在组件挂载后(插入 DOM 树中)立即调用;
shouldComponentUpdate():根据该函数的返回值,来确定组件是否重新渲染;
getSnapshotBeforeUpdate():在最近一次渲染输出(提交到 DOM 节点)之前调用;此生命周期方法的任何返回值将作为参数传递给 componentDidUpdate();
componentDidUpdate():会在更新后会被立即调用,首次渲染不会执行此方法;
componentWillUnmount():会在组件卸载及销毁之前直接调用;
static getDerivedStateFromError():此生命周期会在后代组件抛出错误后被调用。 它将抛出的错误作为参数,并返回一个值以更新 state;它会在渲染阶段调用,因此不允许出现副作用
componentDidCatch():此生命周期在后代组件抛出错误后被调用,会在“提交”阶段被调用,因此允许执行副作用。
父子组件生命周期函数执行顺序:
进入页面:parent-constructor -> parent-getDerivedStateFromProps -> parent-render -> child-constructor -> child-getDerivedStateFromProps -> child-render -> child-componentDidMount -> parent-componentDidMount
更新页面:parent-getDerivedStateFromProps -> parent-shouldComponentUpdate -> parent-render -> child-getDerivedStateFromProps -> child-shouldComponentUpdate -> child-render -> child-componentDidUpdate -> parent-componentDidUpdate
销毁页面:parent-componentWillUnmount -> child-componentWillUnmount