L5:生命周期解释

简述

组件的挂载:React.js将组件渲染,并且构造DOM元素然后塞入页面的过程称为组件的挂载

在React.js中完整的过程是这样:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
-->constructor()
-->componentWillMount()
-->render()
//构造DOM元素插入页面
-->componentDidMount()
//...
//即将从页面中删除
-->componentWillUnmount()
//从页面删除

代码

修改的是 src/index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class Header extends Component{
constructor(){
super()
this.state = {
date:new Date()
}
}
componentWillMount(){
this.timer = setInterval(()=>{
this.setState({date:new Date()})
},1000)
}
componentWillUnmount(){
clearInterval(this.timer);
}
render(){
return(
<div>
<h1>
<p>现在的时间是</p>
{this.state.date.toLocaleTimeString()}
</h1>
</div>
)
}
}
class Index extends Component{
constructor(){
super()
this.state = {
isShowClock : true
}
}
render(){
return (
<div>
{this.state.isShowClock ? <Header /> : null}
<button onClick={()=>{this.setState({isShowClock:!this.state.isShowClock})}}>显示或隐藏</button>
</div>
)
}
}
ReactDOM.render(
<Index />,
document.getElementById('root')
);

组件的更新阶段

1
2
3
4
5
6
7
8
9
/*
shouldComponentUpdata(nextProps,nextState):控制组件是否重新渲染.false组件不会重新渲染。用于性能优化
componentWillReceiveProps(nextProps):组件从父组件接收到新的props之前
componentWillUpdata():组件开始重新渲染之前
componentDidUpdate():组件重新渲染并更改到真实DOM以后引用
*/

大神文章Virtual DOM 算法