Table of Contents
Throw a question
Notes on setState
Problem Analysis
同步更新(函数式setState)
同步异步setState的用法混合
Home Web Front-end JS Tutorial Detailed explanation of the use of setState in React

Detailed explanation of the use of setState in React

May 24, 2018 pm 02:19 PM
react setstate Detailed explanation

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

Throw a question

class Example extends Component {
  contructor () {
    super()
    this.state = {
      value: 0,
      index: 0
    }
  }
  componentDidMount () {
    this.setState({value: this.state.value + 1})
    console.log(this.state.value) // 第一次输出
    this.setState({value: this.state.value + 1})
    console.log(this.state.value) // 第二次输出
    setTimeout(() => {
      this.setState({value: this.state.value + 1})
      console.log(this.state.value) // 第三次输出
      this.setState({value: this.state.value + 1})
      console.log(this.state.value) // 第四次输出
    }, 0);
        this.refs.button.addEventListener('click', this.click)
  }
  click = () => {
    this.setState({value: this.state.index + 1})
    this.setState({value: this.state.index + 1})
  }
  render () {
    return (
      <p><span>value: {this.state.value}index: {this.props.index}</span>
        <button>点击</button>
      </p>
    )
  }
}
Copy after login
  • According to common sense, these four outputs are: 1, 2, 3, 4. However, the actual output is: 0, 0, 2, 3

Notes on setState

  1. setState will not immediately change the state in the React component The value of (that is, setState is an asynchronous update)

  • setState implements state update through a queue mechanism;

  • When setState is executed, The state that needs to be updated will be merged and put into the state queue instead of being updated immediately. The queue can efficiently update the state in batches;

  • If the value is directly modified through this.state, the state will not be updated immediately. Will be put into the state queue. When setState is called next time and the state queue is merged, the state that was directly modified before will be ignored.

  • setState triggers a component update process To trigger redraw

    • Redraw here refers to the update of ReactLife cycleFunction 4 functions:

    • shouldComponentUpdate (this.state is not updated when called; if false is returned, the life cycle is interrupted, and although subsequent functions are not called, the state will still be updated)

    • componentWillUpdate (this.state is not updated when called)

    • render (this.state is updated when called)

    • componentDidUpdate

  • Multiple adjacent state modifications may be merged together and executed at once

  •  this.setState({name: 'Pororo'})
     this.setState({age: 20})
    Copy after login
    • Equal Yu

     this.setState({name: 'Pororo',age: 20})
    Copy after login
    • The effect of the above two blocks of code is the same. If each call triggers a life cycle update, the performance will be very high. Therefore, React will put the modifications generated by multiple this.setState into a queue, and when it is almost the same, it will trigger a life cycle update.

    Problem Analysis

    • For the first two setStates:

    this.setState({value: this.state.val + 1});
    console.log(this.state.value); // 第一次输出
    this.setState({value: this.state.val + 1});
    console.log(this.state.value); // 第二次输出
    Copy after login
    • Since setState does not immediately change the value of state in the React component, this.state.value in setState twice is the same value 0, so the output is 0 both times. Therefore value is only increased by 1.

    • In this case, can this.state be directly manipulated? For example: this.state.value=this.state.value 1;

    • This can indeed modify the status of this.state.value but it cannot cause duplication. render.

    • So, you must change this.state through the setState function set by React, thereby triggering re-rendering.

    • The two setStates in setTimeout:

    setTimeout(() => {
      this.setState({value: this.state.value + 1})
      console.log(this.state.value) // 第三次输出
      this.setState({value: this.state.value + 1})
      console.log(this.state.value) // 第四次输出
    }, 0);
    Copy after login
    • These two times this.state The value is updated synchronously;

    • Synchronously updated: is the event processing triggered by React (for example: the event processing triggered by onClick), Calling setState will update this.state asynchronously;

    • Asynchronous update: Other setState calls will execute this.setState synchronously. "In addition" refers to: bypassing the event processing functions directly added by React through addEventListener and the asynchronous calls generated by setTimeout/setInterval.

    • Illustration of this.setState update mechanism:

    Detailed explanation of the use of setState in React

    • setState is generated every time The new state will be stored in a queue in turn, and then it will be judged based on the isBathingUpdates variable whether to update this.state directly or put it into dirtyComponent and talk about it later.

    • isBatchingUpdates defaults to false, which means setState will update this.state synchronously.

    • 但是,当React在调用事件处理函数之前就会调用batchedUpdates,这个函数会把isBatchingUpdates修改为true,造成的后果就是由React控制的事件处理过程setState不会同步更新this.state。

    同步更新(函数式setState)

    1. 如果this.setState的参数不是一个对象而是一个函数时,这个函数会接收到两个参数,第一个是当前的state值,第二个是当前的props,这个函数应该返回一个对象,这个对象代表想要对this.state的更改;

    2. 换句话说,之前你想给this.setState传递什么对象参数,在这种函数里就返回什么对象。不过,计算这个对象的方法有些改变,不再依赖于this.state,而是依赖于输入参数state。

    function increment(state, props) {
      return {count: state.count + 1};
    }
    function incrementMultiple() {
      this.setState(increment);
      this.setState(increment);
      this.setState(increment);
    }
    Copy after login
    • 假如当前this.state.count的值是0,第一次调用this.setState(increment),传给increment的state参数是0,第二调用时,state参数是1,第三次调用是,参数是2,最终incrementMultiple让this.state.count变成了3。

    • 对于多次调用函数式setState的情况,React会保证调用每次increment时,state都已经合并了之前的状态修改结果。

    要注意的是,在increment函数被调用时,this.state并没有被改变,依然,要等到render函数被重新执行时(或者shouldComponentUpdate函数返回false之后)才被改变。

    同步异步setState的用法混合

    function incrementMultiple() {
      this.setState(increment);
      this.setState(increment);
      this.setState({count: this.state.count + 1});
      this.setState(increment);
    }
    Copy after login
    • 在几个函数式setState调用中插入一个传统式setState调用,最后得到的结果是让this.state.count增加了2,而不是增加4。

    • 这是因为React会依次合并所有setState产生的效果,虽然前两个函数式setState调用产生的效果是count加2,但是中间出现一个传统式setState调用,一下子强行把积攒的效果清空,用count加1取代。

    • 所以,传统式setState与函数式setState一定不要混用。

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

    推荐阅读:

    JS中使用接口步骤详解

    EasyCanvas绘图库在Pixeler项目开发中使用实战总结

    The above is the detailed content of Detailed explanation of the use of setState 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

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    WWE 2K25: How To Unlock Everything In MyRise
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

    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)

    Detailed explanation of the mode function in C++ Detailed explanation of the mode function in C++ Nov 18, 2023 pm 03:08 PM

    Detailed explanation of the mode function in C++ In statistics, the mode refers to the value that appears most frequently in a set of data. In C++ language, we can find the mode in any set of data by writing a mode function. The mode function can be implemented in many different ways, two of the commonly used methods will be introduced in detail below. The first method is to use a hash table to count the number of occurrences of each number. First, we need to define a hash table with each number as the key and the number of occurrences as the value. Then, for a given data set, we run

    Detailed explanation of obtaining administrator rights in Win11 Detailed explanation of obtaining administrator rights in Win11 Mar 08, 2024 pm 03:06 PM

    Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

    Detailed explanation of division operation in Oracle SQL Detailed explanation of division operation in Oracle SQL Mar 10, 2024 am 09:51 AM

    Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

    React Router User Guide: How to implement front-end routing control React Router User Guide: How to implement front-end routing control Sep 29, 2023 pm 05:45 PM

    ReactRouter User Guide: How to Implement Front-End Routing Control With the popularity of single-page applications, front-end routing has become an important part that cannot be ignored. As the most popular routing library in the React ecosystem, ReactRouter provides rich functions and easy-to-use APIs, making the implementation of front-end routing very simple and flexible. This article will introduce how to use ReactRouter and provide some specific code examples. To install ReactRouter first, we need

    Detailed explanation of remainder function in C++ Detailed explanation of remainder function in C++ Nov 18, 2023 pm 02:41 PM

    Detailed explanation of the remainder function in C++ In C++, the remainder operator (%) is used to calculate the remainder of the division of two numbers. It is a binary operator whose operands can be any integer type (including char, short, int, long, etc.) or a floating-point number type (such as float, double). The remainder operator returns a result with the same sign as the dividend. For example, for the remainder operation of integers, we can use the following code to implement: inta=10;intb=3;

    Detailed explanation of the role and usage of PHP modulo operator Detailed explanation of the role and usage of PHP modulo operator Mar 19, 2024 pm 04:33 PM

    The modulo operator (%) in PHP is used to obtain the remainder of the division of two numbers. In this article, we will discuss the role and usage of the modulo operator in detail, and provide specific code examples to help readers better understand. 1. The role of the modulo operator In mathematics, when we divide an integer by another integer, we get a quotient and a remainder. For example, when we divide 10 by 3, the quotient is 3 and the remainder is 1. The modulo operator is used to obtain this remainder. 2. Usage of the modulo operator In PHP, use the % symbol to represent the modulus

    PHP, Vue and React: How to choose the most suitable front-end framework? PHP, Vue and React: How to choose the most suitable front-end framework? Mar 15, 2024 pm 05:48 PM

    PHP, Vue and React: How to choose the most suitable front-end framework? With the continuous development of Internet technology, front-end frameworks play a vital role in Web development. PHP, Vue and React are three representative front-end frameworks, each with its own unique characteristics and advantages. When choosing which front-end framework to use, developers need to make an informed decision based on project needs, team skills, and personal preferences. This article will compare the characteristics and uses of the three front-end frameworks PHP, Vue and React.

    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.

    See all articles