组件的生命周期可分成三个状态:
- Mounting(挂载):已插入真实 DOM
- Updating(更新):正在被重新渲染
- Unmounting(卸载):已移出真实 DOM
挂载 + 卸载
constructor()
componentWillMount() -----> getDerivedStateFromProps()
render()
componentDidMount()
componentWillUnmount()
【demo 演示】
<script type="text/babel">
class Demo extends React.Component {
constructor (props) {
console.log('constructor')
console.log('----------------')
super(props)
}
state = {
count: 0
}
handlePlus = () => {
var targetCount = this.state.count + 1
this.setState({
count: targetCount
})
}
handleUnmount = () => {
ReactDOM.unmountComponentAtNode(document.getElementById("example"))
}
componentWillMount () {
console.log('componentWillMount')
console.log('ref:' + this.countRef)
console.log('state[count]:' + this.state.count)
console.log('----------------')
}
render () {
console.log('render')
console.log('ref:' + this.countRef)
console.log('state[count]:' + this.state.count)
console.log('----------------')
return (
<div>
<div ref={c => this.countRef = c}>{this.state.count}</div>
<button onClick={this.handlePlus}>count++</button>
<button onClick={this.handleUnmount}>unmount</button>
</div>
)
}
componentDidMount () {
console.log('componentDidMount')
console.log('ref:' + this.countRef)
console.log('----------------')
}
componentWillUnmount () {
console.log('componentWillUnmount')
}
}
ReactDOM.render(<Demo />, document.getElementById("example"))
</script>
打印结果:
render() 触发时机:页面初始化 和 state 每次发生更新时
点击3次 count++ 按钮,打印结果如下:
点击3次 unmount 按钮,打印结果如下: