react 组件的什么周期
首先,来一张生命周期图,可以帮助我们更好的理解哦。
来一个具体的实例,看一下react的生命周期的执行顺序到底是怎么样的
<script type="text/babel">
/*
需求: 自定义组件
1. 让指定的文本做显示/隐藏的动画
2. 切换时间为2S
3. 点击按钮从界面中移除组件界面
*/
class Fade extends React.Component {
constructor (props) {
super(props)
console.log('constructor(): 创建组件对象')
this.state = {
opacity: 1
}
this.removeComponent = this.removeComponent.bind(this)
}
componentWillMount () {
console.log('componentWillMount(): 初始化将要挂载')
}
componentDidMount () {// 在此方法中启动定时器/绑定监听/发送ajax请求
console.log('componentDidMount(): 初始化已经挂载')
// 保存到当前组件对象中
this.intervalId = setInterval(function () {
console.log('--------')
// 得到当前opacity
let {opacity} = this.state
// 更新opacity
opacity -= 0.1
if(opacity<=0) {
opacity = 1
}
// 更新状态
this.setState({opacity})
}.bind(this), 200)
}
componentWillUpdate () {
console.log('componentWillUpdate(): 将要更新')
}
componentDidUpdate () {
console.log('componentDidUpdate(): 已经更新')
}
componentWillUnmount () {// 清除定时器/解除监听
console.log('componentWillUnmount(): 将要被移除')
clearInterval(this.intervalId)
}
removeComponent () {
ReactDOM.unmountComponentAtNode(document.getElementById('example'))
}
render() {
console.log('render() 渲染组件')
return (
<div>
<h2 style={{opacity:this.state.opacity}}>{this.props.content}</h2>
<button onClick={this.removeComponent}>不活了</button>
</div>
)
}
}
ReactDOM.render(<Fade content="react学不会, 怎么办?"/>, document.getElementById('example'))
</script>
效果如下:
打印的生命周期顺序是这样的:
注意:这种 ES6类组件(复杂组件) 方式,实际上所有的生命周期都是在 React.Component 这个类里面定义好的,我们写组件的时候,要用到哪些生命周期函数,相当于重写了 React.Component 这个类的方法,就算我们不写,它本身也是有默认的!!!
文章仅为本人学习过程的一个记录,仅供参考,如有问题,欢迎指出!