Table of Contents
Life cycle
componentDidMount
Updating
Note: props cannot be changed manually. The normal scenario is that the current component is called as a child component, and then the props of the component are changed in the parent component
newState: updated state
nextState: state to be updated
nextState: state before update
Unmounting
componentWillUnmount
重新渲染的执行顺序
Home Web Front-end JS Tutorial Detailed explanation of life cycle usage in React

Detailed explanation of life cycle usage in React

May 24, 2018 pm 02:21 PM
react use Detailed explanation

This time I will bring you a detailed explanation of the use of life cycle in React. What are the precautions for using the life cycle in React? Here are practical cases, let’s take a look.

Life cycle

React is a process of rendering virtual DOM into real DOM. This process is called the life cycle of the component. React divides this cycle into three stages, and each stage provides two processing methods: will and did. Will refers to before it happens, and did refers to after it happens.

  • Mounting: Component rendering process

    • componentWillMount()

    • componentDidMount()

  • Updating: Component update process

    • componentWillReceiveProps(nextProps)

    • shouldComponentUpdate(nextProps, nextState)

    • ##componentWillUpdate(object nextProps, object nextState)

    • componentDidUpdate(object prevProps, object prevState)

  • Unmounting: component removal process

    • componentWillUnmount()

    • This stage There is no corresponding did method

Mounting

refers to the first rendering or the re-rendering after the component is removed from the DOM. In the latter scenario, getDefaultProps# will not be executed.

##Execution order

    getDefaultProps
  1. ##getInitialState
  2. ##componentWillMount

  3. render

  4. ##componentDidMount

  5. componentWillMount

    This method is called before render, also That is to say, the real DOM elements cannot be obtained in this method.
  6. This method is triggered before rendering for the first time and before rendering again when state changes.

componentDidMount

This method is called after render, that is, this method can directly obtain the real DOM element.
This method is triggered after the first rendering and after rendering again when the state changes.

var MountingComponent = React.createClass({
    componentWillMount: function(){
        console.log(this.refs.h1) // undefined
    },
    componentDidMount: function(){
        console.log(this.refs.h1) // h1 对象
    },
    render: function(){
        return <h1 ref="h1">Lifecycle-Mounting</h1>;
    }                
})
ReactDOM.render(<MountingComponent />, document.getElementById('p1'));
Copy after login

Updating

It will be triggered when the props or state of the component are changed

Execution sequence

componentWillReceiveProps

  1. shouldComponentUpdate

  2. componentWillUpdate

  3. render

  4. componentDidUpdate

  5. componentWillReceiveProps

    Called when the component receives a new prop. This method will not be called when initializing render.
  6. The method accepts one parameter
newProps: for the updated props

Note: props cannot be changed manually. The normal scenario is that the current component is called as a child component, and then the props of the component are changed in the parent component

shouldComponentUpdate

After the component is mounted, shouldComponentUpdate will be called every time setState is called to determine whether the component needs to be re-rendered. Returns true by default and needs to be re-rendered. In more complex applications, some data changes do not affect the interface display. You can make judgments here to optimize rendering efficiency.
The method accepts two parameters

newProps: updated props

newState: updated state

The method must return boolen. If true is returned, subsequent componentWillUpdate, render, and componentDidUpdate will be executed. Otherwise it will not be executed.


componentWillUpdate

is called when the component receives new props or state but has not yet rendered. Will not be called during initialization.
The method accepts two parameters

nextProps: props to be updated

nextState: state to be updated

componentDidUpdate

Called immediately after the component completes the update. Will not be called during initialization.
The method accepts two parameters

prevProps: props before update

nextState: state before update

var UpdatingComponent = React.createClass({
    getInitialState: function() {
        return {
            data:0
        };
    },           
    setNewNumber: function() {
        //当 state 发生改变的时候,state 对应的组件会重新挂载
        //会触发 componentWillUpdate、componentDidUpdate
        this.setState({data: this.state.data + 1})
    },
    //参数 newProps:已更新的 props
    componentWillReceiveProps:function(newProps) {
        console.log('Component WILL RECEIVE PROPS!', newProps)
    },        
    //参数 newProps:已更新的 props
    //参数 newState:已更新的 state  
    //必须要返回 boolen,true 则执行componentWillUpdate、render、componentDidUpdate。反之则不执行。
    shouldComponentUpdate: function(newProps, newState){
        console.log('shouldComponentUpdate',newProps, newState);
        return (newState.data > 0 && newState.data % 2 == 0);
    },                          
    //参数 nextProps:将要更新的 props
    //参数 nextState:将要更新的 state
    componentWillUpdate: function(nextProps, nextState){
        console.log(nextProps, nextState, this.refs.p1)
    },
    //参数 prevProps:更新前的 props
    //参数 nextState:更新前的 state                
    componentDidUpdate: function(prevProps, prevState){
        console.log(prevProps, prevState) 
    },
    render: function(){
        return (
            <p>
                <button onClick={this.setNewNumber}>INCREMENT</button>
                <h3>{this.state.data}</h3>
            </p>
        );
    }                
})
ReactDOM.render(<UpdatingComponent/>, document.getElementById('p2'));
Copy after login

Unmounting

在组件从 DOM 中移除的时候立刻被调用,这个阶段没有对应的 did 方法

componentWillUnmount

方法适用在父子组件的结构中,当某个条件符合的场景下,该子组件会被渲染

重新渲染的执行顺序

  1. getInitialState

  2. componentWillMount

  3. render

  4. componentDidMount

var ChildrenComponent = React.createClass({
    componentWillUnmount: function(){
        console.log('componentWillUnmount');
    },
    render: function(){
        return <h3>{this.props.myNumber}</h3>
    }
})
var UnmountingComponent = React.createClass({
    getInitialState: function() {
        return {
            data:0
        };
    },
    setNewNumber: function() {
        this.setState({data: this.state.data + 1})
    },
    render: function () {
        var content;
        //当条件不符合时 ChildrenComponent 会被移除,然后会触发方组件的 componentWillUnmount 方法
        //当条件重新符合时,会重新渲染组件 ChildrenComponent
        if(this.state.data % 2 == 0){
            content = <ChildrenComponent myNumber = {this.state.data}></ChildrenComponent>;
        } else {
            content = <h3>{this.state.data}</h3>;
        }
        return (
            <p>
                <button onClick = {this.setNewNumber}>INCREMENT</button>
                {content}
            </p>
        );
    }
})
ReactDOM.render(<UnmountingComponent/>, document.getElementById('p3'));
Copy after login

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

react实现选中li高亮步骤详解

PromiseA+的实现步骤详解


The above is the detailed content of Detailed explanation of life cycle usage in React. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1252
29
C# Tutorial
1225
24
BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? Apr 26, 2024 am 09:40 AM

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

How to use NetEase Mailbox Master How to use NetEase Mailbox Master Mar 27, 2024 pm 05:32 PM

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

How to use Baidu Netdisk app How to use Baidu Netdisk app Mar 27, 2024 pm 06:46 PM

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

How to use Xiaomi Auto app How to use Xiaomi Auto app Apr 01, 2024 pm 09:19 PM

Xiaomi car software provides remote car control functions, allowing users to remotely control the vehicle through mobile phones or computers, such as opening and closing the vehicle's doors and windows, starting the engine, controlling the vehicle's air conditioner and audio, etc. The following is the use and content of this software, let's learn about it together . Comprehensive list of Xiaomi Auto app functions and usage methods 1. The Xiaomi Auto app was launched on the Apple AppStore on March 25, and can now be downloaded from the app store on Android phones; Car purchase: Learn about the core highlights and technical parameters of Xiaomi Auto, and make an appointment for a test drive. Configure and order your Xiaomi car, and support online processing of car pickup to-do items. 3. Community: Understand Xiaomi Auto brand information, exchange car experience, and share wonderful car life; 4. Car control: The mobile phone is the remote control, remote control, real-time security, easy

How to use spaces correctly in Go How to use spaces correctly in Go Mar 29, 2024 pm 03:42 PM

Go language is a simple, efficient, and highly concurrency programming language. It is an open source language developed by Google. In the Go language, the use of spaces is very important, it can improve the readability and maintainability of the code. This article will introduce how to use spaces correctly in Go language and provide specific code examples. Why you need to use spaces correctly In the programming process, the use of spaces is very important for the readability and beauty of the code. Appropriate use of spaces can make code clearer and easier to read, thus reducing

Integration of Java framework and front-end React framework Integration of Java framework and front-end React framework Jun 01, 2024 pm 03:16 PM

Integration of Java framework and React framework: Steps: Set up the back-end Java framework. Create project structure. Configure build tools. Create React applications. Write REST API endpoints. Configure the communication mechanism. Practical case (SpringBoot+React): Java code: Define RESTfulAPI controller. React code: Get and display the data returned by the API.

The definition and use of full-width characters The definition and use of full-width characters Mar 25, 2024 pm 03:33 PM

What are full-width characters? In computer encoding systems, double-width characters are a character encoding method that takes up two standard character positions. Correspondingly, the character encoding method that occupies a standard character position is called a half-width character. Full-width characters are usually used for input, display and printing of Chinese, Japanese, Korean and other Asian characters. In Chinese input methods and text editing, the usage scenarios of full-width characters and half-width characters are different. Use of full-width characters Chinese input method: In the Chinese input method, full-width characters are usually used to input Chinese characters, such as Chinese characters, symbols, etc.

How to use Dewu installment purchase How to use Dewu installment purchase Mar 24, 2024 pm 01:46 PM

How to use Dewu installment purchase? You can use the installment payment service to purchase your favorite goods in Dewu APP. Most people don’t know how to use Dewu installment purchase. Next is the Dewu installment purchase brought by the editor to users. Graphic tutorial on how to use it. Interested users can come and take a look! Dewu usage tutorial How to use Dewu installment purchase 1. First open Dewu APP and enter the main page, select your favorite product and enter the purchase page; 2. Then on the product purchase page in the picture below, click [Buy Now] in the lower right corner; 3 , then select the appropriate code number and click the price on the left; 4. Then on the order confirmation page, select [Submit Order] in the lower right corner; 5. Finally, on the payment page, check the button behind [Huabei Installment]. Just select the installment type and you’re done

See all articles