React Native填坑之旅--組件生命週期

此次咱們來填React Native生命週期的坑。這一點很是重要,須要有一個清晰的認識。若是你瞭解Android或者iOS的話,你會很是熟悉咱們今天要說的的內容。this

基本上一個React Native的組件會經歷三個階段最終渲染在界面上,他們分別是:開始渲染、更新、卸載。code

開始渲染:

componentWillMount

componentWillMount(): void

組件開始渲染的時候調用這個方法component

componentDidMount

componentDidMount(): void

組件的渲染完成以後調用這個方法。子組件的componentDidMount方法會在父組件的前面調用。componentWillMountcomponentDidMount方法以前調用,這個時候組件尚未渲染完成。因此在componentWillMount裏調用setState方法會馬上在render方法裏看到更新了的數據。生命週期

更新

componentWillReceiveProps

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

shouldComponentUpdate(nextProps: Object, nextState: Object): void

當收到新的props或者state的時候觸發這個方法。默認狀況下shouldComponentUpdate一直返回true。這個方法在第一次render的時候不會調用。當你肯定props和state被設置爲新的值之後不須要組件更新的時候返回false。以後render方法在本次的更新中就會被直接跳過,componentWillUpdatecomponentDidUpdate兩個方法也不會被調用。渲染

componentWillUpdate

componentWillUpdate(nextProps: Object, nextState: Object): void

在props或者state更新以後當即調用這個方法。這個方法不會在第一次render的時候調用。date

render

render(): ReactElement<{}>

render方法被調用的時候,組件會根據新的this.propsthis.state繪製。render方法應該是一個純方法。也就是說,它不修改組件的state,而且每次調用都返回相同的結果。固然,這個須要開發者來保證。方法

componentDidUpdate

componentDidUpdate(prevProps: Object, prevState: Object): void

每次組件更新以後調用。第一次render的時候不會調用。next

卸載

componentWillUnmount(): void

組件被卸載以後調用。能夠在這個方法裏執行一些清理操做。

相關文章
相關標籤/搜索