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

這次我們來填React Native生命周期的坑。這一點非常重要,需要有一個清晰的認識。如果你了解Android或者iOS的話,你會非常熟悉我們今天要說的的內容。

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

開始渲染:

componentWillMount

componentWillMount(): void

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

componentDidMount

componentDidMount(): void

組件的渲染完成之后調用這個方法。子組件的componentDidMount方法會在父組件的前面調用。componentWillMountcomponentDidMount方法之前調用,這個時候組件還沒有渲染完成。所以在componentWillMount里調用setState方法會立刻在render方法里看到更新了的數據。

更新

componentWillReceiveProps

componentWillReceiveProps(nextProps: Object): void

當有新的Props發送給組件的時候,這個方法被觸發。最開始的render并不會調用這個方法! 使用這個方法可以在更新state,render方法被調用之前修改組件的props。在這個方法里可以使用this.props來使用舊的props。在這個方法里調用setState方法不會觸發額外的render。

例如:

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的時候調用。

render

render(): ReactElement<{}>

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

componentDidUpdate

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

每次組件更新之后調用。第一次render的時候不會調用。

卸載

componentWillUnmount(): void

組件被卸載之后調用。可以在這個方法里執行一些清理操作。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容