The Component Lifecycle
Each component has several "lifecycle methods" that you can override to run code at particular times in the process. Methods prefixed with **will
** are called right before something happens, and methods prefixed with **did
** are called right after something happens.
Mounting
These methods are called when an instance of a component is being created and inserted into the DOM:
constructor()
componentWillMount()
render()
componentDidMount()
mount 就是第一次讓組件出現(xiàn)在頁(yè)面中的過(guò)程鳍徽。這個(gè)過(guò)程的關(guān)鍵就是 render 方法娄猫。React 會(huì)將 render 的返回值(一般是虛擬 DOM疮跑,也可以是 DOM 或者 null)插入到頁(yè)面中千诬。
這個(gè)過(guò)程會(huì)暴露幾個(gè)鉤子(hook)方便你往里面加代碼:
constructor()
componentWillMount()
render()
componentDidMount()
Updating
mount 之后,如果數(shù)據(jù)有任何變動(dòng),就會(huì)來(lái)到 update 過(guò)程,這個(gè)過(guò)程有 5 個(gè)鉤子:
1.componentWillReceiveProps(nextProps) - 我要讀取 props 啦赫冬!
- shouldComponentUpdate(nextProps, nextState) - 請(qǐng)問(wèn)要不要更新組件?true / false
- componentWillUpdate() - 我要更新組件啦溃列!
- render() - 更新劲厌!
- componentDidUpdate() - 更新完畢啦!
An update can be caused by changes to props or state. These methods are called when a component is being re-rendered:
componentWillReceiveProps()
shouldComponentUpdate()
componentWillUpdate()
render()
componentDidUpdate()
Unmounting
當(dāng)一個(gè)組件將要從頁(yè)面中移除時(shí)听隐,會(huì)進(jìn)入 unmount 過(guò)程补鼻,這個(gè)過(guò)程就一個(gè)鉤子:
componentWillUnmount() - 我要死啦!
你可以在這個(gè)組件死之前做一些清理工作。
This method is called when a component is being removed from the DOM:
componentWillUnmount()