生命周期的鈎子函數
1、組件的定義
什么是組件?當一個頁面所需要呈現出的內容過多,如果我們將所有的頁面寫在同一個.js文件中,會顯得代碼比較亂,給往后的代碼維護造成困難。所以我們在編寫代碼的過程中,將某些部分提取出來,寫在另一個組件中,然后在主頁面中引入這個組件。
組件實際上是代碼封裝的一種,我們可以將經常使用到的一些功能及樣式封裝成一個組件,然后只需要調用這個組件便能調用這些功能和樣式。這樣做既方便了代碼的管理又增加了可維護性。
2、組件的生命周期
在學習組件之前,我們必須先掌握組件的生命周期。一個組件從最開始的引入到最后的消亡,形成一段特殊的生命歷程。這個生命歷程成為組件的生命周期。
(1)componentWillMount
在組件DOM樹渲染前調用。當進入這個組件時執行。
(2)componentDidMount
在組件DOM第一次渲染結束之后執行。
(3)componentWillReceiveProps
在組件接收到新的props時執行。
(4)shouldComponentUpdate
在組件接收到新的props或則執行了this.setState()時執行,它會返回一個布爾值。
(5)componentWillUpdate
在組件接收到新的props或者state但還沒有render時被調用。
(6)componentDidUpdate
在組件完成更新后執行,比如執行this.setState()之后,組件進行刷新。
(7)componentWillUnmount
在組件在DOM中移除,被銷毀后執行。
代碼如下
constructor(props) {
super(props); this.state = { data:"js是世界上最好的語言" }; } render() { return ( <div style={{backgroundColor:"#0ff",fontSize:"20px",color:"#00f"}} onClick={()=>this.click(this.state.data)}> {this.state.data} <a href="http://www.baidu.com">這是百度</a> </div> ) } click=(data)=>{ this.setState({ data:"你說的對!!!" }); }; componentWillMount=()=>{ console.log(1); }; componentDidMount=()=>{ console.log(2); }; componentWillReceiveProps=()=>{ console.log(3); }; shouldComponentUpdate=()=>{ console.log(4); return true; }; componentWillUpdate=()=>{ console.log(5); }; componentDidUpdate=()=>{ console.log(6); }; componentWillUnmount=()=>{ console.log(7); };
- 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
效果如下:
生命周期第三個涉及到接受新的props,以后再說明。第七個銷毀組件時執行,因為涉及到路由跳轉才能看出來,以后再說明。