React.js Tutorial: React Component Lifecycle

Introduction about React component lifecycle.

1 Lifecycle

A React component in browser can be any of the following three statuses: mounted, update and unmounted.

So React component lifecycle can be divided into three phases according to these statuses: mounting, updating and unmounting.

2 Mounting

React.js exposed interfaces or hook methods in each phase of component lifecycle.

2.1 Initializing state

You can optionally set initial state value in constructor() method of the component if you are using ES6 syntax.

const tom_and_jerry = [
    {
        name: ‘Tom‘,
        score: 55
    },
    {
        name: ‘Jerry‘,
        score: 80
    }
];

class ScoreBoard extends React.Component {
    constructor(props) {
        super(props);
        this.state = { players: tom_and_jerry }
    }

    // ...
}

If you are using ES5 syntax, getInitialState() in the right place to initialize component state.

var ScoreBoard = React.createClass({
    getInitialState: function() {
        return {
            players: tom_and_jerry
        }
    },

    // ...
});

The getInitialState() method is called only one time before the component is mounted.

Initialization of state should typically only be done in a top level component, which acts as a role of controller view in your page.

2.2 Default props

You can also define default values of component props (properties) if the parent component does not declare their values.

Return default props using ES7+ static property initializer.

class SinglePlayer extends React.Component {
    static defaultProps = {
        name: ‘Nobody‘,
        score: 0
    }

    // ...
}

Default props in ES6:

class SinglePlayer extends React.Component {
    // ...
}

SinglePlayer.defaultProps = {
    name: ‘Nobody‘,
    score: 0
}

You can define getDefaultProps() method in ES5.

var SinglePlayer = React.createClass({
    getDefaultProps: function() {
        return {
            name: ‘Nobody‘,
            score: 0
        }
    }
});

The getDefaultProps() method is called only once before any instance of the component is created. So you should avoid using this.props inside getDefaultProps() method.

2.3 componentWillMount()

The componentWillMount() method is invoked only once before initial rendering.

It is also a good place to set initial state value inside componentWillMount().

class SinglePlayer extends React.Component {
    componentWillMount() {
        this.setState({
            isPassed: this.props.score >= 60
        });

        alert(‘componentWillMount => ‘ + this.props.name);
        console.log(‘componentWillMount => ‘ + this.props.name);
    }

    // ...
}

2.4 componentDidMount()

This lifecycle method will be invoked after rendering.

It is the right place to access DOM of the component.

class ScoreBoard extends React.Component {
    constructor(props) {
        super(props);
        this._handleScroll = this.handleScroll.bind(this);
    }
    handleScroll() {}
    componentDidMount() {
        alert(‘componentDidMount in NoticeBoard‘);
        window.addEventListener(‘scroll‘, this._handleScroll);
    }

    // ...
}

3 Updating

3.1 componentWillReceiveProps()

void componentWillReceiveProps(object nextProps)

This method will be invoked when a component is receiving new props. componentWillReceiveProps() won‘t be called for the initial rendering.

class SinglePlayer extends React.Component {
    componentWillReceiveProps(nextProps) {
        // Calculate state according to props changes
        this.setState({
            isPassed: nextProps.score >= 60
        });
    }
}

The old props can be accessed via this.props inside componentWillReceiveProps(). Typically, you can set state according to changes of props in this method.

3.2 shouldComponentUpdate()

boolean shouldComponentUpdate(object nextProps,
                              object nextState)

shouldComponentUpdate() will be invoked before rendering when new props or state are being received. This method won‘t be called on initial rendering.

shouldComponentUpdate() returns true by default.

This method is usually an opportunity to prevent the unnecessary rerendering considering performance. Just let shouldComponentUpdate() return false, then the render() method of the component will be completely skipped until the next props or state change.

class SinglePlayer extends React.Component {
    shouldComponentUpdate(nextProps, nextState) {
        // Don‘t rerender if score doesn‘t change,
        if ( nextProps.score == this.props.score ) {
            return false;
        }

        return true;
    }
}

3.3 componentWillUpdate()

void componentWillUpdate(object nextProps,
                         object nextState)

Invoked just before render(), but after shouldComponentUpdate() (of course, return a true). This method is not called for the initial rendering.

Use this as an opportunity to prepare for an update.

class SinglePlayer extends React.Component {
    componentWillUpdate(nextProps, nextState) {
        alert(‘componentWillUpdate => ‘ + this.props.name);
        console.log(‘componentWillUpdate => ‘ + this.props.name);
    }
}

3.4 componentDidUpdate()

void componentDidUpdate(object prevProps,
                        object prevState)

Invoked immediately after the component‘s updates are flushed to the DOM. This method is not called for the initial rendering.

You can perform DOM operations after an update inside this function.

class SinglePlayer extends React.Component {
    componentDidUpdate(prevProps, prevState) {
        alert(‘componentDidUpdate => ‘ + this.props.name);
        console.log(‘componentDidUpdate => ‘ + this.props.name);
    }
}

4 Unmounting

void componentWillUnmount()

This is invoked immediately before a component is unmounted or removed from the DOM.

Use this as an opportunity to perform cleanup operations. For example, unbind event listeners here to avoid memory leaking.

class ScoreBoard extends React.Component {
    componentWillUnmount() {
        window.removeEventListener(‘scroll‘, this._handleScroll);
    }
}

5 Sample codes

Complete sample codes to log each lifecycle method call in browser‘s console.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>React Component Lifecycle Demo</title>
    <!-- react includes two parts: react.js and react-dom.js -->
    <script src="//fb.me/react-15.2.1.js"></script>
    <script src="//fb.me/react-dom-15.2.1.js"></script>

    <!-- babel standalone -->
    <script src="//cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.10.3/babel.min.js"></script>
</head>
<body>
    <div id="app"></div>

    <script type="text/babel">
        const tom_and_jerry = [
            {
                name: ‘Tom‘,
                score: 55
            },
            {
                name: ‘Jerry‘,
                score: 80
            }
        ];

        class SinglePlayer extends React.Component {
            constructor(props) {
                super(props);
                this.state = { isPassed: false }
            }
            componentWillMount() {
                // Mark it as ‘Pass‘ if score >= 60
                this.setState({
                    isPassed: this.props.score >= 60
                });

                console.log(‘componentWillMount => ‘ + this.props.name);
                alert(‘componentWillMount => ‘ + this.props.name);
            }
            componentDidMount() {
                console.log(‘componentDidMount => ‘ + this.props.name);
                alert(‘componentDidMount => ‘ + this.props.name);
            }
            componentWillReceiveProps(nextProps) {
                // Calculate state according to props changes
                this.setState({
                    isPassed: nextProps.score >= 60
                });

                console.log(‘componentWillReceiveProps => ‘ + this.props.name + ‘: ‘ + nextProps.score);
                alert(‘componentWillReceiveProps => ‘ + this.props.name + ‘: ‘ + nextProps.score);
            }
            shouldComponentUpdate(nextProps, nextState) {
                // Don‘t rerender if score doesn‘t change,
                if ( nextProps.score == this.props.score ) {
                    console.log(‘shouldComponentUpdate => ‘ + this.props.name + ‘? false‘);
                    alert(‘shouldComponentUpdate => ‘ + this.props.name + ‘? false‘);
                    return false;
                }

                console.log(‘shouldComponentUpdate => ‘ + this.props.name + ‘? true‘);
                alert(‘shouldComponentUpdate => ‘ + this.props.name + ‘? true‘);
                return true;
            }
            componentWillUpdate(nextProps, nextState) {
                console.log(‘componentWillUpdate => ‘ + this.props.name);
                alert(‘componentWillUpdate => ‘ + this.props.name);
            }
            componentDidUpdate(prevProps, prevState) {
                console.log(‘componentDidUpdate => ‘ + this.props.name);
                alert(‘componentDidUpdate => ‘ + this.props.name);
            }
            componentWillUnmount() {
                console.log(‘componentDidUpdate => ‘ + this.props.name);
                alert(‘componentDidUpdate => ‘ + this.props.name);
            }
            render() {
                console.log("render => " + this.props.name);
                return (
                    <div>
                        <h5><span>Name: </span>{this.props.name}</h5>
                        <p><span>Score: </span><em>{this.props.score}</em></p>
                        <p><span>Pass: </span><input type="checkbox" defaultChecked={this.state.isPassed} disabled={true}  /></p>
                    </div>
                );
            }
        }

        class ScoreBoard extends React.Component {
            constructor(props) {
                super(props);
                this.state = {
                    players: tom_and_jerry
                };
            }
            changeScore(amount) {
                if ( typeof(amount) != "number" ) {
                    return;
                }

                let players = this.state.players;
                let tom = players[0];
                tom.score = tom.score + amount;

                tom.score = (tom.score > 100) ? 100 : tom.score;
                tom.score = (tom.score < 0) ? 0 : tom.score;

                players[0] = tom;
                this.setState({ players: players });
            }
            render() {
                return (
                    <div>
                        <h4>Score Board</h4>
                        <div>
                            <button onClick={ (amount) => this.changeScore(5) }>Score of Tom: +5</button>
                            <button onClick={ (amount) => this.changeScore(-5) }>Score of Tom: -5</button>
                        </div>
                        {
                            this.state.players.map((v, idx) => {
                                return <SinglePlayer key={idx} name={v.name} score={v.score} />
                            })
                        }
                    </div>
                );
            }
        }

        class App extends React.Component {
            render() {
                return (
                    <div>
                        <h1>React Component Lifecycle Demo</h1>
                        <ScoreBoard />
                    </div>
                )
            }
        }

        // Mount root App component
        ReactDOM.render(<App />, document.getElementById(‘app‘));
    </script>
</body>
</html>

https://www.codevoila.com/post/57/reactjs-tutorial-react-component-lifecycle

原文地址:https://www.cnblogs.com/feng9exe/p/11025152.html

时间: 2024-11-05 10:20:42

React.js Tutorial: React Component Lifecycle的相关文章

React.js及React Native知识及实践

一.网络学习资源 官方网站:https://facebook.github.io/react/index.html 中文社区:http://reactjs.cn/ 阮一峰文章:http://www.ruanyifeng.com/blog/2015/03/react.html 百度文库:http://wenku.baidu.com/link?url=asJtxfRP95V11Nnai1b3V-7Vyuduc1ZSda4D3Q5teuIMHc5ShjjiRG-nwLcDG3aRNoSplPlJf9U

React.js入门

React 入门实例教程 现在最热门的前端框架,毫无疑问是 React . 上周,基于 React 的 React Native 发布,结果一天之内,就获得了 5000 颗星,受瞩目程度可见一斑. React 起源于 Facebook 的内部项目,因为该公司对市场上所有 JavaScript MVC 框架,都不满意,就决定自己写一套,用来架设Instagram 的网站.做出来以后,发现这套东西很好用,就在2013年5月开源了. 由于 React 的设计思想极其独特,属于革命性创新,性能出众,代码

React.js Best Practices for 2016

2015 was the year of React with tons of new releases and developer conferences dedicated to the topic all over the world. For a detailed list of the most important milestones of last year, check out our React in 2015 wrap up. The most interesting que

react.js

---恢复内容开始--- 一.React的定义 React 是由Facebook 创建的一个开源项目.它提供了一种在JavaScript中构建用户界面的全新方式.react针对的是现代风格的JavaScript开发生态系统.React 是一个使用JavaScript 和XML技术(可选)构建可组合用户界面的引擎.下面对React定义的每个部分加以详细的说明: React 是一个引擎:React的网站将它定义为一个库,但是我觉得使用"引擎"这个词更能体现出React的核心优势:用来实现响

學習 React.js:用 Node 和 React.js 創建一個實時的 Twitter 流

Build A Real-Time Twitter Stream with Node and React.js By Ken Wheeler (@ken_wheeler) 簡介 歡迎來到學習 React 的第二章,該系列文章將集中在怎麼熟練並且有效的使用臉書的 React 庫上.如果你沒有看過第一章,概念和起步,我非常建議你繼續看下去之前,回去看看. 今天我們準備創建用 React 來創建一個應用,通過 Isomorphic Javascript. Iso-啥? Isomorphic. Java

React JS 基础知识17条

1. 基础实例 <!DOCTYPE html> <html> <head> <script src="../build/react.js"></script> <script src="../build/react-dom.js"></script> <script src="../build/browser.min.js"></script&g

React.js 之hello word

引入的js文件说明 react.js 是 React 的核心库 react-dom.js 是提供与 DOM 相关的功能 babel.min.js的作用是将 JSX 语法转为 JavaScript 语法,这一步很消耗时间,实际上线的时候,应该将它放到服务器完成. 最终效果为

react.js 从零开始(一)

React 是什么? 网络上的解释很多...我这里把他定义为 通过javascript 的形式组件化 html的框架... React 仅仅是 VIEW 层. React 提供了模板语法以及一些函数钩子用于基本的 HTML 渲染.这就是 React 全部的输出——HTML.你把 HTML / JavaScript 合到一起,被称为“组件”,允许把它们自己内部的状态存到内存中(比如在一个选项卡中哪个被选中),不过最后你只是吐出 HTML. React 的安装? 首先是下载 reactjs的文件包.

React Native之React速学教程(上)

概述 本篇为<React Native之React速学教程>的第一篇.本篇将从React的特点.如何使用React.JSX语法.组件(Component)以及组件的属性,状态等方面进行讲解. What's React React是一个用于组建用户界面的JavaScript库,让你以更简单的方式来创建交互式用户界面. 当数据改变时,React将高效的更新和渲染需要更新的组件.声明性视图使你的代码更可预测,更容易调试. 构建封装管理自己的状态的组件,然后将它们组装成复杂的用户界面.由于组件逻辑是用