0x00 前言
文中工具皆可关注 皓月当空w 公众号 发送关键字 工具 获取
0x01 生命周期
1.基本概念
当Clock组件第一次被渲染到DOM的时候,为其设置一个计时器,这一个被称为挂载(mount)
当Clock组件被删除的时候,移除计时器,被称为卸载(unmount)
2.组件卸载
<script type="text/babel">
class Life extends React.Component{
state={opactity:1}
death=()=>{
ReactDOM.unmountComponentAtNode(document.getElementById('test'))
}
render(){
return (
<div>
<h2 stytle={{opactity:this.state.opactity}}>React 学不会怎么办</h2>
<button onClick={this.death}>不活了</button>
</div>
)
}
}
ReactDOM.render(<Life/>,document.getElementById('test'))
</script>
3.组件第一次挂载 componentDidmount
<script type="text/babel">
class Life extends React.Component{
state={opacity:0.5}
death=()=>{
ReactDOM.unmountComponentAtNode(document.getElementById('test'))
}
componentDidmount(){
setInterval(() => {
let {opacity} =this.state
opacity -=0.1
if (opacity<=0) opacity = 1
this.setState({opacity})
}, 200);
}
render(){
return (
<div>
<h2 style={{opacity:this.state.opacity}}>React 学不会怎么办</h2>
<button onClick={this.death}>不活了</button>
</div>
)
}
}
ReactDOM.render(<Life/>,document.getElementById('test'))
</script>
4.组件卸载
<script type="text/babel">
class Life extends React.Component{
state={opacity:1}
death=()=>{
ReactDOM.unmountComponentAtNode(document.getElementById('test'))
}
componentDidMount(){
this.timer=setInterval(() => {
let {opacity} =this.state
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'))
</script>
0x02 旧版生命周期
Demo
<script type="text/babel">
class Count extends React.Component{
constructor(props){
console.log("constructor")
super(props)
this.state={count:0}
}
add=()=>{
const{count}=this.state
this.setState({count:count+1})
console.log(count)
}
death=()=>{
ReactDOM.unmountComponentAtNode(document.getElementById('test'))
}
force=()=>{
console.log("forceUpdate")
this.forceUpdate()
}
componentWillMount(){
console.log("componentWillMount")
}
componentDidMount(){
console.log("componentDidMount")
}
componentWillUnmount(){
console.log("componentWillUnmount")
}
shouldComponentUpdate(){
console.log("shouldComponentUpdate")
return true
}
componentWillUpdate(){
console.log("componentWillUpdate")
}
componentDidUpdate(){
console.log("componentDidUpdate")
}
render(){
console.log("render")
const{count} = this.state
return(
<div>
<h2>当前求和为:{count}</h2>
<button onClick={this.add}>点我+1</button>
<button onClick={this.death}>卸载</button>
<button onClick={this.force}>强制更新</button>
</div>
)
}
}
ReactDOM.render(<Count/>,document.getElementById('test'))
</script>
0x03 新生命周期
other
欢迎大家关注我朋友的公众号 皓月当空w 分享漏洞情报以及各种学习资源,技能树,面试题等。
以上