組件的生命周期可分成三個狀態: Mounting:已插入真實 DOMUpdating:正在被重新渲染Unmounting:已移出真實 DOM 生命周期的方法有:componentWillMount 在渲染前調用,在客戶端也在服務端。componentDidMount : 在第一次渲染後調用,只在客戶 ...
組件的生命周期可分成三個狀態:
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 中移除之前立刻被調用。
【定時器實例】
import React, { Component,Fragment } from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; import PropTypes from 'prop-types'; class Hello extends Component{ constructor(props){ super(props); this.state={ opacity:1 } } componentDidMount(){ this.timer=setInterval(()=>{ var opacity=this.state.opacity; opacity-=0.05; if(opacity<0.1){ opacity=1; } this.setState({ opacity:opacity }) },100); } render(){ return( <Fragment> <div style={{opacity:this.state.opacity}}>hello react</div> </Fragment> ) } } ReactDOM.render( <div> <Hello /> </div>, document.getElementById('example') ); serviceWorker.unregister();
以下實例初始化 state , setNewnumber 用於更新 state。所有生命周期在 Content 組件中。
import React, { Component,Fragment } from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; import PropTypes from 'prop-types'; class AddFn extends Component{ constructor(props){ super(props); this.state={ num:0 } this.addNum=this.addNum.bind(this); } addNum(){ this.setState({ num:this.state.num+1 }) } render(){ return( <Fragment> <button onClick={this.addNum}>點擊計數</button> <Text num={this.state.num} /> </Fragment> ) } } class Text extends Component{ constructor(props){ super(props); } componentWillMount(){ console.log('組件將要掛載'); } componentDidMount(){ console.log('組件掛載完成'); } componentWillReceiveProps(newProps){ console.log('組件將要接收參數'); } shouldComponentUpdate(newProps,newState){ return true; } componentWillUpdate(){ console.log('組件將要更新'); } componentDidUpdate(){ console.log('組件更新完成'); } componentWillUnmount(){ console.log('組件將要卸載'); } render(){ return( <div>{this.props.num}</div> ) } } ReactDOM.render( <div> <AddFn /> </div>, document.getElementById('example') ); serviceWorker.unregister();