react初步学习三

React 生命周期

React 生命周期分成两类:

  • 当组件在挂载或卸载时;

  • 当组件接收新的数据时,即组件更新时

组件挂载

组件状态的初始化
初始化组件

import React, { Component, PropTypes } from 'react';
class App extends Component {
    static propTypes = {   
        // ...   
    }; 
    static defaultProps = {
        // ...
    };
    constructor(props) {
        super(props);
        this.state = {
            // ... 
        };
    } 
    componentWillMount() {
            // ...
        } 

    componentDidMount() {
            // ...
        } 
    render() {
        return <div>This is a demo.</div>;
    }
}

componentWillMount 方法会在 render 方法之前执行
componentDidMount 方法会在 render 方法之后执行
在 componentWillMount 中执行 setState 方法——无意义

组件卸载

import React, { Component, PropTypes } from 'react';
class App extends Component {
    componentWillUnmount() {
        // ...
    }
    render() {
        return <div>This is a demo.</div>;
    }
}

事件回收或是清除定时器

猜你喜欢

转载自blog.csdn.net/a839371666/article/details/81304704