1. 程式人生 > >React.js掛載階段的元件生命週期

React.js掛載階段的元件生命週期

元件的掛載指的是將元件渲染並且構造 DOM 元素然後插入頁面的過程。這是一個從無到有的過程,React.js 提供一些生命週期函式可以給我們在這個過程中做一些操作。

React.js 將元件渲染,並且構造 DOM 元素然後塞入頁面的過程稱為元件的掛載。這一節我們學習了 React.js 控制組件在頁面上掛載和刪除過程裡面幾個方法:

  • componentWillMount:元件掛載開始之前,也就是在元件呼叫 render 方法之前呼叫。
  • componentDidMount:元件掛載完成以後,也就是 DOM 元素已經插入頁面後呼叫。
  • componentWillUnmount:元件對應的 DOM 元素從頁面中刪除之前呼叫。

總結
我們一般會把元件的 state 的初始化工作放在 constructor 裡面去做;
在 componentWillMount 進行元件的啟動工作,例如 Ajax 資料拉取、定時器的啟動;
元件從頁面上銷燬的時候,有時候需要一些資料的清理,例如定時器的清理,就會放在 componentWillUnmount 裡面去做。
例子
完成 Post 元件,它可以載入、重新整理文章內容。

已有函式 getPostData,它會返回一個 Promise,你可以通過它獲取文章的內容。

getPostData().then((postContent) => {
  // ...
})

在獲取資料的時候,Post 元件的 div.post-content 中顯示 資料載入中…,完成載入以後直接顯示 getPostData 的返回結果。

頁面有個按鈕,點選可以重新載入資料。

class Post extends Component {
  constructor(){
    super();
    this.state={
      content:''
    }
  }
  componentWillMount(){
    this.setState({content:'資料載入中...'});
  }
  handleClick(){
    this
.setState({content:'資料載入中...'}); getPostData().then((postContent) => { this.setState({content:postContent}); }) } componentDidMount(){ getPostData().then((postContent) => { this.setState({content:postContent}); }) } render () { return ( <div> <div className='post-content'>{this.state.content}</div> <button onClick={this.handleClick.bind(this)}>重新整理</button> </div> ) } }

以上是區域性程式碼片段。