个人 尚硅谷React全家桶学习笔记(十三)
37.引出生命周期
class Life extends React.Component{
state={
opacity:1
}
death=()=>{
//卸载组件
ReactDOM.unmountComponentAtNode(document.getElementById('test'))
}
//组件挂载完毕后调用 并且只调用一次
componentDidMount(){
this.timer=setInterval(() => {
//获取原状态
let{opacity}=this.state
//减小0.1
opacity-=0.1
if(opacity<=0) opacity=1
//设置新的透明度
this.setState({opacity})
},200);
}
//组件将要卸载时调用一次
componentWillUnmount(){
//清除定时器
clearInterval(this.timer)
}
render(){
return(
<div>
<h2 style={
{opacity:this.state.opacity}}>React学不会怎么办?</h2>
<button onClick={this.death}>不活了</button>
</div>
)
}
}
ReactDOM.render(<Life/>,document.getElementById('test'))
在合适的时机 调用函数
例如 componentDidMount() 是在函数挂载完毕后调用且只调用一次的函数
componentWillUnmount() 是在组件卸载前调用且只调用一次的函数
1.组件从创建到死亡会经历一些特定的阶段。
2.React组件中包含一系列勾子函数(生命周期回调函数),会在特定时刻调用。
3.我们在定义组件时,会在特定的生命周期回调函数中做特定的工作。
38.生命周期(旧)_组件挂载流程
class Count extends React.Component{
//构造器
constructor(props){
console.log('Count-constructor');
super(props)
}
//组件将要挂载的钩子
componentWillMount(){
console.log('