1. 組件的生命週期
組件的生命週期可分成三個狀態:
- Mounting:已插入真是DOM
- Updating: 真該被重新渲染
- Unmounting:已移出真實DOM
組件的生命週期狀態:說明在不同時機訪問組件,組件正處在生命週期的不同狀態上。在不同的生命週期狀態訪問,就產生不同的方法。
生命週期的方法如下:
- 裝載組件觸發:componentWillMount在渲染前調用,在客戶端也在服務端,只會在裝載之前調用一次;componentDidMount在第一此渲染後調用,只在客戶端。之後組件已經生成了對應的DOM結構,可以通過this.getDomNode來進行訪問。如果你想和其他JavaScript框架一起使用,可以在這個方法中調用setTimeout,setInterval或者發送AJAX請求等操作(阻止異步操作阻塞UI)。只在裝載完成後調用一次,在render之後。
- 更新組件觸發——這些方法不會在首次render組件的週期調用。componentWillReceiveProps(nextProps)在組件接收到一個新的prop時被調用。這個方法在初始化render時不會被調用。shouldComponentUpdate(nextProps, nextState)返回一個布爾值,在組件接收到新的prpos或者state時被調用。在初始化時或者使用forceUpdate時不被調用。可以在你確認不需要更新組件時使用;如果設置爲false,就是不允許更新組件,那麼componenWillUpdate、componentDidUpdate不會執行。componentWillUpdate(nextProps, nextState)在組件接收新的props或者state但還沒有render時被調用,在初始化時不會被調用。componentDidUpdate(preProps, preState) 在組件完成更新後立即調用,在初始化時不會被調用。
- 卸載組件觸發:componentWillUnmount在組件從DOM中移除的時候立即被調用。
import React from 'react'
import ReactDom from 'react-dom'
class Root extends React.Component{
constructor(props){
super(props)
this.state = {flag: true, count: 0}
console.log('Root constructor~~~')
}
componentWillMount(...args){
console.log('will mount', args)
}
componentDidMount(...args){
console.log('did mount', args)
}
componentWillUnmount(...args){
console.log('will unmount', args)
}
// update
componentWillReceiveProps(nextProps){
console.log(' will receive props', this.props, nextProps)
}
shouldComponentUpdate(nextProps, nextState){
// console.log('should update', this.props, nextProps)
console.log('should update', this.state, nextState)
// return nextProps.count > 3?true: false
return (nextProps.count > 3 || nextState.count > 3)?true:false
// 注意:nextPState看似return false拒絕,但是要知道只是沒有render,state的值還是還是被更新了
}
componentWillUpdate(nextProps, nextState){
// console.log('will update', this.props, nextProps)
console.log('will update', this.state, nextState)
}
handleClick(e){
this.setState({count: this.state.count + 1})
}
render(){
console.log('Root render~~~~~~')
return <div onClick={this.handleClick.bind(this)}>金州勇士</div>
}
componentDidUpdate(preProps, preState){
// console.log('did update', this.props, preProps)
console.log('did update', this.state, preState)
}
}
class App extends React.Component{
constructor(props){
super(props)
this.state = {count: 0}
}
handleClick(e){
this.setState({count: this.state.count + 1})
}
render(){
return <div onDoubleClick={this.handleClick.bind(this)}>
<Root count={this.state.count} />
count = {this.state.count}
</div>
}
}
ReactDom.render(
<App />,
document.getElementById('root')
)
由圖可知:constructor構造器是最早執行的函數。組件構建好之後,如果更新組件的state或props(注意在組件內props是隻讀的),就會render渲染前觸發一系列的更新生命週期函數。