1. 父子組件的生命週期執行過程
1.1 首次渲染的過程
父constructor => 父componentWillMount => 父render =>
遇到子組件進入子組件的生命週期 => 子constructor =>
子componentWillMount => 子render =>
子componentDidMount => 父componentDidMount
1.2 數據更新
數據更新主要是通過兩個生命週期函數:componentWillReceiveProps和shouldComponentUpdate。這裏可以思考一個問題:demo裏面當點擊div時,傳遞給子組件的值變化。當我們不做任何處理的時候,子組件無法獲取到父組件值的變化,那子組件怎麼感應到父組件的值變化從而自動更新呢?
1.2.1 componentWillReceiveProps
這個生命週期主要是當父組件中改變了props傳值時觸發的函數,可以來使子組件隨父組件自動更新。父組件re-render也會導致其子組件走更新流程(不管此時父組件傳給子組件的props有沒有改變),這種方式則是要走componentWillReceiveProps這步的。
1.2.2 shouldComponentUpdate
shouldComponentUpdate(nextProps, nextState):可以通過這個方法控制組件是否重新渲染。如果返回 false 組件就不會重新渲染。這個生命週期在 React.js 性能優化上非常有用。
2. 面試過程中可能出現的問題
2.1 react中有什麼生命週期,怎麼執行的?
執行一次的生命週期函數:constructor,componentWillMount,componentDidMount ,componentDidUnMount 。
多次執行的函數:render,componentWillReceiveProps,shouldComponentUpdate
2.2 父組件中包含子組件,在渲染的時候,它們生命週期執行的順序?
答案:首次渲染中的描述
2.3 在父組件傳遞給子組件數據時候,如果父類傳遞的props更新的時候,子類自動更新?
- 採用componentWillReceiveProps,可以把父類的props屬性賦值給子類的state, 然後在componentWillReceiveProps執行的時候判斷,如果props更新了,則執行setSate更新相應的state.
// 父類
render(){
return (
<div>
<div onClick={() => this.handleClick('count')}>點我count{this.state.count}</div>
<div onClick={() => this.handleClick('num')}>點我num{this.state.num}</div>
<Child count={this.state.count}></Child>
</div>
)
}
// 子類
componentWillReceiveProps(nextProps){
console.log('父組件傳遞的值')
if(this.props.count !== nextProps.count){
console.log(this.props.count)
this.setState({
childCount: nextProps.count
})
}
}
render(){
console.log('03子數據渲染render')
return (
<div>{this.state.childCount}</div>
)
}
- shouldComponentUpdate好像做不到???
2.4 在父組件re-render時候,默認情況下,自組件是不是一定會re-render。
是的,一定會,不管從父類獲得的props有無變化,其實這裏子類不需要更新,這就需要優化,這就需要在子組件中增加shouldComponentUpdate, 判斷props是否發生變化,如果沒有變化就返回false,不需要更新。
// 父類
render(){
return (
<div>
<div onClick={() => this.handleClick('count')}>點我count{this.state.count}</div>
<div onClick={() => this.handleClick('num')}>點我num{this.state.num}</div>
<Child count={this.state.count}></Child>
</div>
)
}
// 子類
//
shouldComponentUpdate(nextProps,nextState){
console.log('01子組件是否要更新數據')
if(this.props.count === nextProps.count){
return false
}
return true
render(){
console.log('03子數據渲染render')
return (
<div>{this.state.childCount}</div>
)
}