React的生命周期
React中组件有生命周期,也就是说也有很多钩子函数供我们使用, 组件的生命周期,我们会分为四个阶段,初始化、运行中、销毁、错误处理(16.3之后)
初始化
在组件初始化阶段会执行
- constructor (用来定义状态,或者是用来放一些this的方法的)
- static getDerivedStateFromProps() ----将来会使用(定义一个状态,这个状态将来会使用)
- componentWillMount() / UNSAFE_componentWillMount() ----带有 UNSAFE属于过时的钩子函数(老版本的)
componentWillMount()会在17版本后启用,使用static getDerivedStateFromProps() - render()
- componentDidMount()(组件挂载结束)
更新阶段
props或state的改变可能会引起组件的更新,组件重新渲染的过程中会调用以下方法:
- componentWillReceiveProps() / UNSAFE_componentWillReceiveProps() (属性发生改变)
- static getDerivedStateFromProps()(属性发生改变触发)
- shouldComponentUpdate() // react性能优化第二方案 (组件应该更新么)
- componentWillUpdate() / UNSAFE_componentWillUpdate()
- render()
- getSnapshotBeforeUpdate() (快照)
- componentDidUpdate()(组件更新结束)
卸载阶段
1. componentWillUnmount()
错误处理
1. componentDidCatch() --16.3版本之后出现的
各生命周期详解
1.constructor(props)
通过super来继承父类身上传递过来的属性,然后当前组件