React應用在初始化和更新的過程當中,會通過一系列的邏輯,React在不一樣的邏輯時期會執行不一樣的生命週期函數,用來給咱們作一些處理。babel
這幾個生命週期函數的用法以下:函數
對於componentWillMount和componentDidMount來講它們是沒有參數的,並且一個組件掛載時只會執行一次。測試
舉個栗子,需求:定義了兩個組件:App組件和Person組件,App組件引用了Person組件而且傳入了一個名爲no的props,另外在App組件和Person組件內都定義了一個button按鈕,分別用於修改Person組件的props和state變化,另外咱們在Person組件內分別定義了上面講解到的4個生命週期函數,代碼以下:this
<div id="root"></div> <script type="text/babel"> class Person extends React.Component{ //定義一個子組件Person constructor(props){ super(props); this.state = {no:props.no+100} } componentWillMount(){ console.log('trigger:componentWillMounted'); } componentDidMount(){ console.log('trigger:componentDidMount'); } componentWillUpdate(newProps,newState){ console.log('trigger:componentDidMount newprops=',newProps,' newState=',newState) } componentDidUpdate(newPros,newState){ console.log('trigger:componentDidUpdate'); } render (){ return <div> <button onClick={e=>this.setState({no:this.state.no+1})}>子組件按鈕(用於修改state)</button> <p>props.no:{this.props.no}</p> <p>state.no:{this.state.no}</p> </div> } } class App extends React.Component{ //定義一個父組件App,它會引用子組件,而且修改子組件的props constructor(props){ super(props) } state = {no:1} render(){ return <div> <button onClick={e=>this.setState({no:this.state.no+1})}>父組件按鈕(用於修改props)</button> <Person no={this.state.no} /> </div> } } ReactDOM.render(<App/>,root) </script>
最終頁面渲染以下:spa
初始化時控制檯打印以下:code
表示在Person組件加載過程當中分別觸發了componentWillMount和componentDidMount生命週期函數,由於咱們在Person組件就打印了這兩個信息,而後咱們點擊第一個按鈕,看看輸出信息:component
writer by:大沙漠 QQ:22969969blog
父組件的按鈕對應的事件是每次點擊時傳遞的no遞增1,咱們可在Person組件內的componentWillUpdate內打印了newProps,能夠看到no發生了變化,每點擊一次,componentWillUpdate觸發一次,而且Person組件的props.no遞增了1。生命週期
同理,咱們點擊一下第二個按鈕,會觸發Person組件的事件,會修改Person組件的state,並觸發從新渲染,以下:事件
一樣的,點擊後也觸發了Person組件內的componentWillUpdate生命週期函數,將新的props和state打印了出來,咱們能夠看到state發生了變化。
ComponentWillUpdate的第三個參數是context發生變化時新的context的值,有興趣的本身寫個demo測試一下就行了,我就不貼了。
對於這四個生命週期函數來講,咱們只能在事件觸發收作一些與主線無關的操做,什麼是主線無關呢,好比componentWillUpdate是React將要更新的時候觸發的,我可不能夠返回false,這樣React就不會繼續更新,而是中止下來了呢,React也提供了這樣的生命週期函數,叫作shouldComponentUpdate生命週期函數,固然React還有其它的一些生命週期函數,咱們一個個講解。