React 元件生命週期

在本章節中我們將討論 React 元件的生命週期。

元件的生命週期可分成三個狀態:

  • Mounting:已插入真實 DOM
  • Updating:正在被重新渲染
  • Unmounting:已移出真實 DOM

生命週期的方法有:

  • componentWillMount 在渲染前呼叫,在客戶端也在服務端。

  • componentDidMount : 在第一次渲染後呼叫,只在客戶端。之後元件已經生成了對應的DOM結構,可以通過this.getDOMNode()來進行訪問。 如果你想和其他JavaScript框架一起使用,可以在這個方法中呼叫setTimeout, setInterval或者傳送AJAX請求等操作(防止非同步操作阻塞UI)。

  • componentWillReceiveProps 在元件接收到一個新的 prop (更新後)時被呼叫。這個方法在初始化render時不會被呼叫。

  • shouldComponentUpdate 返回一個布林值。在元件接收到新的props或者state時被呼叫。在初始化時或者使用forceUpdate時不被呼叫。
    可以在你確認不需要更新元件時使用。

  • componentWillUpdate在元件接收到新的props或者state但還沒有render時被呼叫。在初始化時不會被呼叫。

  • componentDidUpdate 在元件完成更新後立即呼叫。在初始化時不會被呼叫。

  • componentWillUnmount在元件從 DOM 中移除之前立刻被呼叫。

這些方法的詳細說明,可以參考官方文件。

以下例項在 Hello 元件載入以後,通過 componentDidMount 方法設定一個定時器,每隔100毫秒重新設定元件的透明度,並重新渲染:

React 例項

class Hello extends React.Component { constructor(props) { super(props); this.state = {opacity: 1.0}; } componentDidMount() { this.timer = setInterval(function () { var opacity = this.state.opacity; opacity -= .05; if (opacity < 0.1) { opacity = 1.0; } this.setState({ opacity: opacity }); }.bind(this), 100); } render () { return ( <div style={{opacity: this.state.opacity}}> Hello {this.props.name} </div> ); } } ReactDOM.render( <Hello name="world"/>, document.body );

嘗試一下 ?

以下例項初始化 statesetNewnumber 用於更新 state。所有生命週期在 Content 元件中。

React 例項

class Button extends React.Component { constructor(props) { super(props); this.state = {data: 0}; this.setNewNumber = this.setNewNumber.bind(this); } setNewNumber() { this.setState({data: this.state.data + 1}) } render() { return ( <div> <button onClick = {this.setNewNumber}>INCREMENT</button> <Content myNumber = {this.state.data}></Content> </div> ); } } class Content extends React.Component { componentWillMount() { console.log('Component WILL MOUNT!') } componentDidMount() { console.log('Component DID MOUNT!') } componentWillReceiveProps(newProps) { console.log('Component WILL RECEIVE PROPS!') } shouldComponentUpdate(newProps, newState) { return true; } componentWillUpdate(nextProps, nextState) { console.log('Component WILL UPDATE!'); } componentDidUpdate(prevProps, prevState) { console.log('Component DID UPDATE!') } componentWillUnmount() { console.log('Component WILL UNMOUNT!') } render() { return ( <div> <h3>{this.props.myNumber}</h3> </div> ); } } ReactDOM.render( <div> <Button /> </div>, document.getElementById('example') );

嘗試一下 ?