React: React component life cycle

I. Introduction

Life cycle of components while doing a presentation in front of Western Ontario The second blog post, but the overall feeling is too simple to say, after all, is a core part of the life cycle React assembly. In the course of our skilled use React to mount and synthetic components to create the presentation layer of the application, or for asynchronous data latency problem, only make full use of the life cycle of components to seize the opportunity to load and data processing framework, in order to play the component performance to a reasonable level, and improve the robustness of the application. Basically, the life cycle of components can be divided into mount life cycle and life-cycle update two parts, which include a series of methods that will be triggered before and after the component rendering, in fact, render the method itself is component lifecycle a part of. Of course, the user is using ES6 class to create components or React.createClass create components that reflect the life cycle of a little bit of difference. Components created using React.createClass, developers can default initialization properties and state and the getDefalutProps getInitialState functions respectively, while using ES6 class to create components, these two functions are replaced by a constructor constructors, you get the default constructor inside property and setting state. Complete life cycle shown in FIG comparison:

  

Second, Detailed

1, Mount Lifecycle

Methods comprising: constructor / getDefault / getInitialState, componentWillMount, render, componentDidMount, componentWillUnmout.

2, update life cycle

包括方法有:componentWillReceiveProps、shouldComponentUpdate、componentWillUpdate、componentDidUpdate。 

 

Third, examples

1、React.createClass

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Hello React</title>
    <script src="react/react.js"></script>
    <script src="react/react-dom.js"></script>
    <script src="react/browser.min.js"></script>
</head>
<body>
    <div id="container"></div>
    <script type="text/babel">

        const targetNode = document.getElementById("container");

        const Component = React.createClass({

            getDefaultProps(){
                console.log("---getDefaultProps---");
                return {}
            },

            getInitialState(){
                console.log("---getInitialState---");
                return ({
                    count: 0
                })
            },

            componentWillMount(){
                console.log("---componentWillMount---")
            },

            render(){
                console.log("---render---");
                return (
                    <div>
                        <h1>{`${this.props.title} ${this.state.count}`}</h1>
                    </div>
                )
            },

            componentDidMount(){
                console.log("---componentDidMount---");
                this.setProps({
                    title:"I AM XYQ! Welcome me, current count is"
                })
            },
            /*
            * 现象:父组件更新子组件的props,在子组件接收到新的props时,更新子组件的state,但是却没有重新渲染。
            * 原因:官方说在该函数中调用 this.setState() 将不会引起第二次渲染。每次子组件接收到新的props,都会重新渲染一次,
            * 除非你做了处理来阻止(比如使用:shouldComponentUpdate)。 但是你可以在这次渲染前,根据新的props更新state,
            * 更新state也会触发一次重新渲染,但react基于性能考虑,只会渲染一次。
            * */
            componentWillReceiveProps(nextProps){
                console.log("---componentWillReceiveProps---");
                this.setState({
                    count: this.state.count + 1
                })
            },

            shouldComponentUpdate(nextProps, nextState){
                console.log("---shouldComponentUpdate---"+`count is ${nextState.count}`);
                return true
            },

            componentWillUpdate(nextProps, nextState){
                console.log("---componentWillUpdate---")
            },

            componentDidUpdate(nextProps, nextState){
                console.log("---componentDidUpdate---");
                ReactDOM.unmountComponentAtNode(targetNode); //卸载根组件
            },

            componentWillUnmount(){
                console.log("---componentWillUnmout---");
            }

        });

        ReactDOM.render(
            <Component/>,
            targetNode
        )

    </script>
</body>
</html>

结果与分析  【需要把ReactDOM.unmountComponentAtNode()方法注释掉才会显示结果,不然组件就从DOM上卸载了】

2、ES6 

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Hello React</title>
    <script src="react/react.js"></script>
    <script src="react/react-dom.js"></script>
    <script src="react/browser.min.js"></script>
</head>
<body>
    <div id="container"></div>
    <script type="text/babel">

        const targetNode = document.getElementById("container");

        //父组件
        class Parent extends React.Component {

            constructor(props){
                super(props)
                this.state = {title:""}
                this.deleteComponent = this.deleteComponent.bind(this)
            };

            deleteComponent(){
                ReactDOM.unmountComponentAtNode(targetNode); //卸载根组件
            }

            render(){
                return (
                    <div onClick={this.deleteComponent}>
                        <Children name={this.state.title}/>
                    </div>)
            };

            //父组件修改传递给子组件的属性值,子组件会触发componentWillReceiveProps函数
            componentDidMount(){
                this.setState({
                    title: "I AM XYQ! Welcome me, current count is"
                })
            };
        }

        //子组件
        class Children extends React.Component{

            constructor(props){
                super(props);
                this.state = {count:0};
                console.log("---constructor---")
            };

            componentWillMount(){
                console.log("---componentWillMount---")
            };

            render(){
                console.log("---render---");
                return (
                    <h1>{`${this.props.name} ${this.state.count}`}</h1>
                )
            };

            componentDidMount(){
                console.log("---componentDidMount---");
            };

            //此处获取的nextProps就是父组件的state中的title属性
            componentWillReceiveProps(nextProps){
                console.log("---componentWillReceiveProps---");
                this.setState({
                    count: this.state.count + 1
                })
            };

            shouldComponentUpdate(nextProps, nextState){
                console.log("---shouldComponentUpdate---"+`count is ${nextState.count}`);
                return true
            };

            componentWillUpdate(nextProps, nextState){
                console.log("---componentWillUpdate---")
            };

            componentDidUpdate(nextProps, nextState){
                console.log("---componentDidUpdate---");
            };

            componentWillUnmount(){
                console.log("---componentWillUnmout---");
            }
        }

        ReactDOM.render(
            <Parent/>,
            targetNode
        )

    </script>
</body>
</html>

结果与分析  【点击deleteComponent()事件,组件就从DOM上卸载了】

 

Guess you like

Origin www.cnblogs.com/XYQ-208910/p/12009830.html