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

    Video Face Swap

    Video Face Swap

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

    Hot Article

    Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    Nordhold: Fusion System, Explained
    4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
    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)

    Hot Topics

    Java Tutorial
    1670
    14
    PHP Tutorial
    1274
    29
    C# Tutorial
    1256
    24
    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.

    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

    Vue.js vs. React: Project-Specific Considerations Vue.js vs. React: Project-Specific Considerations Apr 09, 2025 am 12:01 AM

    Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

    React's Role in HTML: Enhancing User Experience React's Role in HTML: Enhancing User Experience Apr 09, 2025 am 12:11 AM

    React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

    React vs. Vue: Which Framework Does Netflix Use? React vs. Vue: Which Framework Does Netflix Use? Apr 14, 2025 am 12:19 AM

    Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

    React's Ecosystem: Libraries, Tools, and Best Practices React's Ecosystem: Libraries, Tools, and Best Practices Apr 18, 2025 am 12:23 AM

    The React ecosystem includes state management libraries (such as Redux), routing libraries (such as ReactRouter), UI component libraries (such as Material-UI), testing tools (such as Jest), and building tools (such as Webpack). These tools work together to help developers develop and maintain applications efficiently, improve code quality and development efficiency.

    The Future of React: Trends and Innovations in Web Development The Future of React: Trends and Innovations in Web Development Apr 19, 2025 am 12:22 AM

    React's future will focus on the ultimate in component development, performance optimization and deep integration with other technology stacks. 1) React will further simplify the creation and management of components and promote the ultimate in component development. 2) Performance optimization will become the focus, especially in large applications. 3) React will be deeply integrated with technologies such as GraphQL and TypeScript to improve the development experience.

    See all articles