react新版本生命周期
一. 初始化阶段
* 1. constructor
* 2. getDerivedStateFromProps
* 3. render
* 4. componentDidMount
二 更新阶段
* 1. getDerivedStateFromProps
* 2. shouldComponentUpdate
* 3. render
* 4. getSnapsHotBeofreUpdate
* 5. componentDidUpdate
三. 销毁阶段
* 1. componentWillUnmount
代码(可复制直接运行)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app"></div>
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<script src="https://cdn.bootcss.com/babel-standalone/6.22.1/babel.min.js"></script>
<script type="text/babel">
class Life extends React.Component {
constructor (props) {
super(props)
this.state = {
count: 0
}
console.log("Demo--- constructor")
}
// 更新组件
handleClick = ()=> {
this.setState({
count: this.state.count + 1
})
}
// 强制更新组件
force = ()=> {
this.forceUpdate()
}
// 销毁
destruction = ()=> {
ReactDOM.unmountComponentAtNode(document.getElementById("app"))
}
// 若state的值在任何时候都取决于props 可以使用 必须返回一个状态对象 或者 一个null
static getDerivedStateFromProps(props, state) {
console.log("getDerivedStateFromProps", props, state)
return null
}
// 在更新之前获取快照
getSnapshotBeforeUpdate(preProps, preState) {
console.log("getSnapsHotBeofreUpdate", preProps, preState)
// 将返回值返回了componentDidUpdate
return '1111'
}
// 组件挂载完毕的钩子
componentDidMount() {
console.log('Demo组件挂载完毕--- componentDidMount')
}
// 控制组件更新的"开关" 必须返回一个Boolean
shouldComponentUpdate() {
console.log('Demo控制组件更新的"开关"--- shouldComponentUpdate')
return true
}
// 组件更新完毕的钩子
componentDidUpdate(preProps, preState, snapshotValue){
console.log('Demo组件更新完毕--- componentDidUpdate',preProps,preState, snapshotValue)
}
// 组件销毁的钩子
componentWillUnmount(){
console.log('Demo--- componentWillUnmount')
}
render() {
console.log('Demo--- render')
return (
<div>
<div>当前和为{this.state.count}</div>
<button onClick={this.handleClick}>点我加1</button>
<button onClick={this.force}>强制更新</button><br/>
<button onClick={this.destruction}>点我销毁</button>
</div>
)
}
}
ReactDOM.render(
<Life/>,
document.getElementById('app')
);
</script>
</body>
</html>