react18版本生命周期
组件挂载时
- constructor
- static getDerivedStateFromProps(纯函数,静态方法)
- render
- componentDidMount
数据更新时
- static getDerivedStateFromProps
- shouldComponentUpdate
- render
- getSnapshotBeforeUpdate
- componentDidUpdate
组件卸载时
捕获父子组件异常时
新增生命周期
- static getDerivedStateFromProps
- getSnapshotBeforeUpdate
从v16.3开始弃 componentWillMount、componentWillReceiveProps 、componentWillUpdate 三个钩子函数
import React, { Component } from 'react'
export default class index extends Component {
constructor(props) {
console.log("constructor============1");
super();
this.state = {
msg: '这是更新前'
}
}
componentDidMount() {
console.log("componentDidMount=========================3");
}
componentDidUpdate() {
console.log('更新时');
}
componentWillUnmount() {
console.log('卸载时');
}
componentDidCatch() {
console.log("捕捉到异常了");
}
static getDerivedStateFromProps(nextProps, prevState) {
console.log(nextProps, prevState, "纯函数,静态方法");
return null
}
getSnapshotBeforeUpdate(prevProps, prevState) {
console.log(prevProps, prevState, "需要搭配 componentDidUpdate来使用");
return null
}
shouldComponentUpdate() {
console.log('是否更新当前组件数据');
return false
}
setDate = () => {
this.setState({
msg: '这是更新后'
})
}
render() {
console.log("render====================2");
return (
<div>
<button onClick={this.setDate}>{this.state.msg}</button>
</div>
)
}
}