react生命周期
分为三个大的周期
Mounting(挂载):已插入真实 DOM
Updating(更新):正在被重新渲染
Unmounting(卸载):已移出真实 DOM
1: 挂载 constructor(): 在 React 组件挂载之前,会调用它的构造函数。
getDerivedStateFromProps(): 在调用render方法之前调用,并且在初始挂载及后续更新时都会被调用。
render(): render() 方法是 class 组件中唯一必须实现的方法。
componentDidMount(): 在组件挂载后(插入 DOM 树中)立即调用。
2: 更新阶段
当props和state的时候会执行
getDerivedStateFromProps(): 在调用 render 方法之前调用,并且在初始挂载及后续更新时都会被调用。根据 shouldComponentUpdate() 的返回值,判断 React 组件的输出是否受当前 state 或 props 更改的影响。
shouldComponentUpdate():当 props 或state发生变化时,shouldComponentUpdate 会在渲染执行之前被调用。
render(): render() 方法是 class 组件中唯一必须实现的方法。
getSnapshotBeforeUpdate(): 在最近一次渲染输出(提交到 DOM 节点)之前调用。 componentDidUpdate(): 在更新后会被立即调用。 3: 卸载时候
componentWillUnmount(): 在组件卸载及销毁之前直接调用
hooks生命周期
1: useState(react: constructor ) // 存储数据的地方 componentDidMount,componentDidUpdate,componentWillUnmount
2: useEffect (进入页面进行调用)相当于react中的
3: getDerivedStateFromProps
4: shouldComponentUpdate (面试当中会问到)
5: render (渲染数据)
当父组件数据更新的时候子组件的生命周期执行顺序
进入页面:
父组件: constructor -> 父组件-getDerivedStateFromProps -> 父组件-render -> 子组件-constructor -> 子组件-getDerivedStateFromProps -> 子组件-render -> 子组件-componentDidMount -> 父组件-componentDidMount
更新页面:
父组件: getDerivedStateFromProps -> 父组件-shouldComponentUpdate -> 父组件-render -> 子组件-getDerivedStateFromProps -> 子组件-shouldComponentUpdate -> 子组件-render -> 子组件-componentDidUpdate -> 父组件-componentDidUpdate
销毁页面:
父组件: componentWillUnmount -> 子组件-componentWillUnmount