React生命周期
前言
在React中组件的生命周期会经历三个过程:
- 挂载(Mount),第一次在DOM树渲染
- 更新(Update),组件被重新渲染
- 卸载(Unmount),组件在DOM树中删除
这里是不同阶段生命周期执行顺序:
初始化:
在组件初始化阶段会执行
- constructor
- static getDerivedStateFromProps()
- componentWillMount() / UNSAFE_componentWillMount()
- render()
- componentDidMount()
更新阶段:
props或state的改变可能会引起组件的更新,组件重新渲染的过程中会调用以下方法:
- componentWillReceiveProps() / UNSAFE_componentWillReceiveProps()
- static getDerivedStateFromProps()
- shouldComponentUpdate()
- componentWillUpdate() / UNSAFE_componentWillUpdate()
- render()
- getSnapshotBeforeUpdate()
- componentDidUpdate()
卸载阶段:
- componentWillUnmount()
在react中生命周期一共有这样几个:
1、组件将要挂载时触发:componentWillMount
2、组件挂载完成时触发:componentDidMount
3、是否要更新数据时触发:shouldComponentUpdate
4、将要更新数据时触发:componentWillUpdate
5、数据更新完成时触发:componentDidUpdate
6、组件将要销毁时触发:componentWillUnmount
7、父组件中改变了props传值时触发:componentWillReceiveProps
8、错误处理:componentDidCatch()
因为有些钩子是要被废弃的,所以在书写时必须在前面加UNSAFE_才不会有这样的警告,比如:UNSAFE_componentWillMount
在v16.4中不同阶段生命周期执行是这样的:
react 12个生命周期函数,各个函数的细节详解可看这篇文章:
https://blog.csdn.net/g1437353759/article/details/109014040