## 十、組件的生命周期
組件的[生命周期](https://facebook.github.io/react/docs/working-with-the-browser.html#component-lifecycle)分成三個狀態:
* Mounting:已插入真實 DOM
* Updating:正在被重新渲染
* Unmounting:已移出真實 DOM
React 為每個狀態都提供了兩種處理函數,will 函數在進入狀態之前調用,did 函數在進入狀態之后調用,三種狀態共計五種處理函數。
* componentWillMount()
* componentDidMount()
* componentWillUpdate(object nextProps, object nextState)
* componentDidUpdate(object prevProps, object prevState)
* componentWillUnmount()
此外,React 還提供兩種特殊狀態的處理函數。
* componentWillReceiveProps(object nextProps):已加載組件收到新的參數時調用
* shouldComponentUpdate(object nextProps, object nextState):組件判斷是否重新渲染時調用
這些方法的詳細說明,可以參考[官方文檔](http://facebook.github.io/react/docs/component-specs.html#lifecycle-methods)。下面是一個例子(查看?[demo10](https://github.com/ruanyf/react-demos/blob/master/demo10/index.html)?)。
> ~~~
> var Hello = React.createClass({
> getInitialState: function () {
> return {
> opacity: 1.0
> };
> },
>
> componentDidMount: function () {
> 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: function () {
> return (
> <div style={{opacity: this.state.opacity}}>
> Hello {this.props.name}
> </div>
> );
> }
> });
>
> React.render(
> <Hello name="world"/>,
> document.body
> );
> ~~~
上面代碼在hello組件加載以后,通過 componentDidMount 方法設置一個定時器,每隔100毫秒,就重新設置組件的透明度,從而引發重新渲染。
另外,組件的style屬性的設置方式也值得注意,不能寫成
> ~~~
> style="opacity:{this.state.opacity};"
> ~~~
而要寫成
> ~~~
> style={{opacity: this.state.opacity}}
> ~~~
這是因為?[React 組件樣式](https://facebook.github.io/react/tips/inline-styles.html)是一個對象,所以第一重大括號表示這是 JavaScript 語法,第二重大括號表示樣式對象。