1. 程式人生 > 程式設計 >面試官常問React的生命週期問題

面試官常問React的生命週期問題

React的生命週期

兩張圖帶你理解 React的生命週期

React的生命週期(舊)

在這裡插入圖片描述

class Life extends React.Component{
      // 構造器
      constructor(ZdEySiETprops){
        console.log('Life構造器---constructor');
        super(props)
        this.state={num:0}
      }
      // 計算+1功能
      add=()=>{
        const {num} = this.state
        this.setState({num:num+1})
      }
      // 刪除元件
      death=()=>{
        ReactDOM.www.cppcns.com
unmountComponentAtNode(document.getElementById('text')) } force=()=>{ this.forceUpdate() } // 將要掛載 componentWillMount(){ console.log('Life將要掛載---componentWillMohttp://www.cppcns.comunt'); } // 已經掛載 componentDidMount(){ console.log('Life已經掛載---componentDidMount'); } // 刪除觸發 componentWillUnmount(){ console.log('Life刪除觸發---componentWillUnmount'); } // 是否應該改變資料 shouldComponentUpdate(){ console.log('Life是否改變資料---shouldComponentUpdate'); return true } // 將要改變資料 componentWillUpdate(){ console.log('Life將要改變資料---componentWillUpdate'); } // 改變資料 componentDidUpdate(){ console.log('Life改變資料---componentDidUpdate'); } render(){ console.log('Life---render'); const {num} = this.state return( <div> <h1>計數器:{num}</h1> <button onClick={this.add}>點我+1</button> <button onClick={this.death}>刪除</button> <button onClick={this.force}>不更改任何狀態的資料,強制更新</button> </div> ) } } // 渲染頁面 ReactDOM.render(<Life />,document.getElementById('text'))

掛載步驟

在這裡插入圖片描述

更新步驟

在這裡插入圖片描述

刪除

在這裡插入圖片描述

總結: 初始化階段: 由ReactDOM.render()觸發—初次渲染
1. constructor() ---構造器
2. componentWillMount() ---將要掛載
3. render() ---render
4. componentDidMount() ---掛載時更新階段: 由元件內部this.setSate()或父元件重新render觸發
1. shouldComponentUpdate() ---是否要進行更改資料
2. componentWillUpdate() ---將要更新資料
3. render()
4. componentDidUpdate() ---更新資料

解除安裝元件: 由ReactDOM.unmountComponentAtNode()觸發
componentWillUnmount() ---解除安裝

React的生命週期(新)

請新增圖片描述

生命週期的三個階段(新)

初始化階段: 由ReactDOM.render()觸發—初次渲染
1. constructor()
2. getDerivedStateFromProps
3. render()
4. componentDidMount()更新階段: 由元件內部this.setSate()或父元件重新render觸發
1. getDerivedStateFromProps
2. shouldComponentUpdate()
3. render()
4. getSnapshotBeforeUpdate
5. componentDidUpdate()解除安裝元件: 由ReactDOM.unmountComponentAtNode()觸發
1. componentWillUnmount()

重要的勾子

1.render:初始化渲染或更新渲染呼叫
2.componentDidMount:開啟監聽,傳送ajax請求
3.componentWillUnmount:做一些收尾工作,如: 清理定時器

即將廢棄的勾子

1.componentWillMount
2.componentWillReceiveProps
3.componentWillUpdate

現在使用會出現警告,下一個大版本需要加上UNSAFE_字首才能使用,以後可能會被徹底廢棄,不建議使用。

到此這篇關於面試官常問React的生命週期問題的文章就介紹到這了,更多相關React生命週期內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!