隨便扯扯React生命周期 --《愛看不看系列》
生命周期嘛,顧名思義,就是說組件這輩子從生下來到死掉經歷的事情。先來看看一張圖片,溫故溫故,如圖:
你會發現有些周期的名字都能找出點規律,我找到的規律是凡是 Will 字母的,表示該鉤子函數會在該生命周期發生之前調用;包含前綴did
表示該鉤子函數會在該生命周期發生之後調用。
大概給生命周期分及各類:
1、Mounting(掛載)
- constructor()
- componentWillMount()
- render()
- componentDidMount()
上面幾個函數會在組件被創建和插入到DOM後調用
2、Updating(更新)
componentWillReceiveProps()
shouldComponentUpdate()
componentWillUpdate()
render()
componentDidUpdate()
props 或者 state 的變化都會導致更新。上面這些方法會在 組件 重新渲染時調用。
3、Unmounting
componentWillUnmount()
該方法將會在 組件 從DOM中移除時調用
分完類之後就來依次說說各個組件是幹什麽的咯,怕是每個寫react的程序員都會有自己的見解咯。
1. componentWillMount()
這個組件個人覺得爭議很大,有的人說可以在這個鉤子函數內寫ajax請求,有的說不行,我還是保持我自己的觀念,
不能在裏面使用setState方法來更新組件,因為它是在render函數之前執行的,也就是說執行它的時候,DOM節點
是還沒有掛在的,強行setState會導致React Component 的 re-render。
2. componentDidMount()
這個函數在組件掛在之後執行的,所以比較適合用作初始化DOM節點的操作和AJAX請求。
在該鉤子函數裏面,可以使用 setState 但是會觸發重新渲染 re-render 。
3.componentWillReceiveProps(nextProps)
該鉤子函數將會在已掛載組件(mounted component)接收到新的 props 之前調用。適用於更新state的值(重新渲染)
比較this.props和nextProps。有一個要註意的地方就是,props即使沒有變化,也會調用這個鉤子函數,所以,一般我們的
做法就是比較this.props和nextProps。
4.shouldComponentUpdate(nextProps, nextState)
當組件接收到新的 Props 或者 state時,要進行 rendering之前會調用 shouldComponentUpdate()
。該鉤子函數用於告訴 React 組件是否需要重新渲染。
shouldComponentUpdate()
默認返回 true
。
shouldComponentUpdate()
在兩種情況下不會被調用:1、初始化渲染;2、使用了forceUpdate()方法。
但是當 shouldComponentUpdate()
返回 false
的時候,此時 state 發生改變,並不能阻止 child component 進行重新渲染。
但是一旦 shouldComponentUpdate()
返回 false
,這就意味著 componentWillUpdate()
、 render()
和 componentDidUpdate()
將不再執行。
5.componentWillUpdate()
state or props 更新後re-render之前調用。
不能在這裏調用 setState
,如果需要設置 state,應該在 componentWillReceiveProps()
中調用 setState()
.
6.componentDidUpdate
在組件更新之後馬上調用。在該鉤子函數內,你可以:1、操作DOM;2、發起網絡請求
7.componentWillUnmount
在組件卸載和銷毀前調用。在該鉤子函數內可以做一些清除工作,比如:1、取消定時器;2、取消網絡請求;3、綁定DOM事件。
隨便扯扯React生命周期 --《愛看不看系列》