此次咱們來填React Native生命週期的坑。這一點很是重要,須要有一個清晰的認識。若是你瞭解Android或者iOS的話,你會很是熟悉咱們今天要說的的內容。this
基本上一個React Native的組件會經歷三個階段最終渲染在界面上,他們分別是:開始渲染、更新、卸載。code
componentWillMount(): void
組件開始渲染的時候調用這個方法component
componentDidMount(): void
組件的渲染完成以後調用這個方法。子組件的componentDidMount
方法會在父組件的前面調用。componentWillMount
在componentDidMount
方法以前調用,這個時候組件尚未渲染完成。因此在componentWillMount
裏調用setState
方法會馬上在render
方法裏看到更新了的數據。生命週期
componentWillReceiveProps(nextProps: Object): void
當有新的Props發送給組件的時候,這個方法被觸發。最開始的render並不會調用這個方法! 使用這個方法能夠在更新state,render
方法被調用以前修改組件的props。在這個方法裏可使用this.props
來使用舊的props。在這個方法裏調用setState
方法不會觸發額外的render。開發
例如:class
componentWillReceiveProps(nextProps) { this.setState({ currentCategory: nextProps.category !== this.props.category ? nextProps.category : this.props.category }); }
shouldComponentUpdate(nextProps: Object, nextState: Object): void
當收到新的props或者state的時候觸發這個方法。默認狀況下shouldComponentUpdate
一直返回true。這個方法在第一次render的時候不會調用。當你肯定props和state被設置爲新的值之後不須要組件更新的時候返回false
。以後render
方法在本次的更新中就會被直接跳過,componentWillUpdate
和componentDidUpdate
兩個方法也不會被調用。渲染
componentWillUpdate(nextProps: Object, nextState: Object): void
在props或者state更新以後當即調用這個方法。這個方法不會在第一次render的時候調用。date
render(): ReactElement<{}>
當render
方法被調用的時候,組件會根據新的this.props
和this.state
繪製。render
方法應該是一個純方法。也就是說,它不修改組件的state,而且每次調用都返回相同的結果。固然,這個須要開發者來保證。方法
componentDidUpdate(prevProps: Object, prevState: Object): void
每次組件更新以後調用。第一次render的時候不會調用。next
componentWillUnmount(): void
組件被卸載以後調用。能夠在這個方法裏執行一些清理操做。