這次我們來填React Native生命周期的坑。這一點非常重要,需要有一個清晰的認識。如果你了解Android或者iOS的話,你會非常熟悉我們今天要說的的內容。
基本上一個React Native的組件會經歷三個階段最終渲染在界面上,他們分別是:開始渲染、更新、卸載。
開始渲染:
componentWillMount
componentWillMount(): void
組件開始渲染的時候調用這個方法
componentDidMount
componentDidMount(): void
組件的渲染完成之后調用這個方法。子組件的componentDidMount
方法會在父組件的前面調用。componentWillMount
在componentDidMount
方法之前調用,這個時候組件還沒有渲染完成。所以在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
方法在本次的更新中就會被直接跳過,componentWillUpdate
和componentDidUpdate
兩個方法也不會被調用。
componentWillUpdate
componentWillUpdate(nextProps: Object, nextState: Object): void
在props或者state更新之后立即調用這個方法。這個方法不會在第一次render的時候調用。
render
render(): ReactElement<{}>
當render
方法被調用的時候,組件會根據新的this.props
和this.state
繪制。render
方法應該是一個純方法。也就是說,它不修改組件的state,并且每次調用都返回相同的結果。當然,這個需要開發者來保證。
componentDidUpdate
componentDidUpdate(prevProps: Object, prevState: Object): void
每次組件更新之后調用。第一次render的時候不會調用。
卸載
componentWillUnmount(): void
組件被卸載之后調用。可以在這個方法里執行一些清理操作。