生命周期函数指在某一个时刻组件会自动调用执行的函数
image.png
生命周期图详解
- lnitialization 初始化过程
props state
- Mounting 挂载
.1 componentWillMount(){}在组件即将被挂载到页面的时刻自动执行
.2 render(){}页面挂载
.3 componentDidMount() {}在组件挂载到页面之后自动被执行
- Updation 更新
props 和 state 共有生命周期函数
.1 shouldComponentUpdate() {}组件被更新之前
.2 componentWillUpdate() {}
组件被更新之前, 但shouldComponentUpdate 执行后并返回为true才会执行
.3 render(){}页面挂载
.4 componentDidUpdate() {}组件被更新完成之后 (render执行之后) 他会执行
- props
.1 componentWillReceiveProps() {}
特殊的! 1.一个组件要从父组件接收参数,2.如果这个组件第一次存在与父组件中不执行 3.如果这个组件之前已经存在与父组件中执行
- Unmounting 页面去除
.1 componentWillUnmount() {}当这个组件即将被从页面中剔除的时候,会被执行
代码解释
import React, {Component} from 'react'
class Cycle extends Component {
constructor(props) {
super(props)
this.state = ({
inputValue: ''
})
this.inputChange = this.inputChange.bind(this)
this.inputSubmit = this.inputSubmit.bind(this)
}
// 在组件即将被挂载到页面的时刻自动执行
componentWillMount() {
console.log('componentWillMount = 1')
}
// 页面挂载
render() {
console.log('render = 2')
return (
<div>
<input onChange={this.inputChange} value={this.state.inputValue}/>
<button onClick={this.inputSubmit}>提交</button>
</div>
)
}
// 在组件挂载到页面之后自动被执行
componentDidMount() {
console.log('componentDidMount = 3')
}
/* 一个组件要从父组件接收参数
* 如果这个组件第一次存在与父组件中不执行
* 如果这个组件之前已经存在与父组件中执行
*/
componentWillReceiveProps() {
console.log('组件被更新 componentWillReceiveProps = 0')
}
// 组件被更新之前,他会自动被执行
shouldComponentUpdate() {
console.log('组件被更新 shouldComponentUpdate = 1')
return true //返回true 需要被更新, false 不需要被更新
}
// 组件被更新之前,他会自动被执行, 但它在 shouldComponentUpdate 执行之后并返回为true才会执行
componentWillUpdate() {
console.log('组件被更新 componentWillUpdate = 2')
}
// 组件被更新完成之后 (render执行之后) 他会执行
componentDidUpdate(prevProps, prevState, snapshot) {
console.log('组件被更新之后 componentDidUpdate = 3')
}
// 当这个组件即将被从页面中剔除的时候,会被执行
componentWillUnmount() {
console.log('组件被剔除 componentWillUnmount')
}
inputChange(e) {
const value = e.target.value
this.setState(() => ({
inputValue: value
}))
}
inputSubmit(){
console.log(this.state.inputValue)
}
}
export default Cycle
网友评论