A brief analysis of React's understanding of state

A brief analysis of React's understanding of state

How to define complex components (class components) and simple components (function components)?

  • Whether it has state

This raises the question, what is state?

For example, I failed the exam today because I was not in a good state, and my state affected my behavior .
The state in the component drives the page update. In other words, the component state stores data, and changes in the data drive the page update.

insert image description here

What we need to understand here is, whose state is it? The state is the state of the component instance object, not the component class itself, but the instance created by this class.

(class) One of the three major attributes on the component instance: state

Display content

insert image description here

Realize a requirement, by clicking the page, hot/cool switch

insert image description here
insert image description here

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>react</title>
  </head>
  <body>
    <div id="test"></div>
    <!-- Import core library-->
    <script src="../js/react.development.js"></script>
    <!-- Extension Library -->
    <script src="../js/react-dom.development.js"></script>
    <!-- Convert jsx to js -->
    <script src="../js/babel.min.js"></script>
    <script type="text/babel">
      // 1. Create component class Weather extends React.Component {
        /**
         * What data can be received in the constructor depends on what data is passed when new is called. * New Weather is not operated by us, but by react. */
        constructor(props) {
          // I haven't learned props yet, but I have to use it. I'll imitate the official website to write // The class syntax super(props);
          // In the constructor, this points to the constructor instance object // Before 16.8, state is {}, and after 16.8, it is null
          this.state = {
            isHot: true,
          };
        }
        render() {
          console.log("this:", this);
          return <h1>It is very hot today</h1>;
        }
      }
      // 2. Render components to the page ReactDOM.render(<Weather />, document.getElementById("test"));
    </script>
  </body>
</html> 

insert image description here

Initialize Data

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>react</title>
  </head>
  <body>
    <div id="test"></div>
    <!-- Import core library-->
    <script src="../js/react.development.js"></script>
    <!-- Extension Library -->
    <script src="../js/react-dom.development.js"></script>
    <!-- Convert jsx to js -->
    <script src="../js/babel.min.js"></script>
    <script type="text/babel">
      // 1. Create component class Weather extends React.Component {
        /**
         * What data can be received in the constructor depends on what data is passed when new is called. * New Weather is not operated by us, but by react. */
        constructor(props) {
          // I haven't learned props yet, but I have to use it. I will imitate the official website to write it, otherwise it won't work. // Class syntax super(props);
          // In the constructor, this points to the constructor instance object // Before 16.8, state is {}, and after 16.8, it is null
          this.state = {
            isHot: true,
          };
        }
        // state is on the Weather instance object render() {
          console.log("this:", this);
          return <h1>Today's weather is very {this.state.isHot ? "hot" : "cool"}</h1>;
        }
      }
      // 2. Render components to the page ReactDOM.render(<Weather />, document.getElementById("test"));
    </script>
  </body>
</html> 

insert image description here

Next, write the click event. Note that we will first make an error demonstration.

 <script type="text/babel">
      // 1. Create component class Weather extends React.Component {
        /**
         * What data can be received in the constructor depends on what data is passed when new is called. * New Weather is not operated by us, but by react. */
        constructor(props) {
          // I haven't learned props yet, but I have to use it. I'll imitate the official website to write // The class syntax super(props);
          // In the constructor, this points to the constructor instance object // Before 16.8, state is {}, and after 16.8, it is null
          this.state = {
            isHot: true,
          };
        }

        // state is on the Weather instance object render() {
          console.log("this:", this);
          return (
            <h1 onClick={demo()}>
              Today's weather is {this.state.isHot ? "hot" : "cool"}
            </h1>
          );
        }
      }
      function demo() {
        console.log("demo is called");
      }
      // 2. Render components to the page ReactDOM.render(<Weather />, document.getElementById("test"));
    </script>

When I call the click event, I write onClick={demo()}
In the console, you will find that the function is executed immediately.

insert image description here

When react calls the render method through the instance in new Weather, if you want to get the return value, you need to execute <h1 onClick={demo()}>Today's weather is very {this.state.isHot ? "热" : "凉"}</h1>. When the onClick assignment statement is executed , the return value of the demo() function call is given to onClick as a callback. The return value of demo() is undifend, that is, undifend is given to onClick as a callback. This is a wrong approach because adding () after demo leads to a function call. **When the click occurs, undifend is called, and react handles this process. If it is undifend, there will be no extra actions.

Common writing errors

  render() {
          console.log("this:", this);
          return (
            <h1 onClick='demo()'>Today's weather is {this.state.isHot ? "hot" : "cool"}</h1>
          );
        } 

insert image description here

 render() {
          console.log("this:", this);
          return (
            <h1 onclick='demo'>Today's weather is {this.state.isHot ? "hot" : "cool"}</h1>
          );
        } 

insert image description here

Correct writing

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>react</title>
  </head>
  <body>
    <div id="test"></div>
    <!-- Import core library-->
    <script src="../js/react.development.js"></script>
    <!-- Extension Library -->
    <script src="../js/react-dom.development.js"></script>
    <!-- Convert jsx to js -->
    <script src="../js/babel.min.js"></script>
    <script type="text/babel">
      // 1. Create component class Weather extends React.Component {
        /**
         * What data can be received in the constructor depends on what data is passed when new is called. * New Weather is not operated by us, but by react. */
        constructor(props) {
          // I haven't learned props yet, but I have to use it. I'll imitate the official website to write // The class syntax super(props);
          // In the constructor, this points to the constructor instance object // Before 16.8, state is {}, and after 16.8, it is null
          this.state = {
            isHot: true,
          };
        }

        // state is on the Weather instance object render() {
          console.log("this:", this);
          return (
            <h1 onClick={demo}>
              Today's weather is {this.state.isHot ? "hot" : "cool"}
            </h1>
          );
        }
      }
      function demo() {
        console.log("demo is called");
      }
      // 2. Render components to the page ReactDOM.render(<Weather />, document.getElementById("test"));
    </script>
  </body>
</html> 

insert image description here

Revise

The data has been rendered to the page above, and now we want to modify the data on the page. If you want to modify the data, you must first get isHot in the state. Let's look at an incorrect way of writing :

 function demo() {
        console.log("demo is called");
        // Error demonstration const { isHot } = this.state;
        console.log("isHot", isHot);
      } 

insert image description here

The prompt is xxx of undefined (reading 'state'), which means state of undefined. When xxx is undefined, undefined.state will report this error. The xxx here refers to this.
Let's print this

  function demo() {
        // Error demonstration console.log("this", this);
        const { isHot } = this.state;
        console.log("isHot", isHot);
      } 

insert image description here

Let's take a look at the code structure and comments

insert image description here

insert image description here

Through printing, it is found that when the custom function is placed outside the class, the data can be displayed correctly, but the data in the state cannot be obtained/modified.

  class Weather extends React.Component {
        /**
         * What data can be received in the constructor depends on what data is passed when new is called. * New Weather is not operated by us, but by react. */
        constructor(props) {
          // I haven't learned props yet, but I have to use it. I'll imitate the official website to write // The class syntax super(props);
          /**
           * In the constructor, this points to the constructor instance object. * Before 16.8, state is {}, and after 16.8, it is null
           * state is in the instance object of Weather */
          this.state = {
            isHot: true,
          };
        }
        // Switch weather demo() {
          console.log("this", this);
          const { isHot } = this.state;
          console.log("isHot", isHot);
        }
        // Rendering render() {
          console.log("this:", this);
          return (
            <h1 onClick={demo}>
              Today's weather is {this.state.isHot ? "hot" : "cool"}
            </h1>
          );
        }
      }

Note that a class is not a function body, so you don’t need to write function

This concludes this article on a brief analysis of React’s understanding of state. For more information on React state understanding, please search 123WORDPRESS.COM’s previous articles or continue browsing the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Deep understanding of React State principles
  • Detailed explanation of the abbreviation of state in react
  • Detailed explanation of react setState
  • In-depth study of setState source code in React
  • In-depth understanding of the working mechanism of react's setState
  • How much do you know about state and setState() in React components?

<<:  Detailed steps to install and uninstall Apache (httpd) service on centos 7

>>:  Example to explain the size of MySQL statistics table

Recommend

Tutorial on installing and using virtualenv in Deepin

virtualenv is a tool for creating isolated Python...

How to install Maven automatically in Linux continuous integration

Unzip the Maven package tar xf apache-maven-3.5.4...

Solve the problem that PhpStorm fails to connect to VirtualBox

Problem description: When phpstorm's SFTP hos...

Basic operations on invisible columns in MySQL 8.0

Table of contents 01 Create invisible columns 02 ...

Native JS to achieve sliding button effect

The specific code of the sliding button made with...

MySQL 8.0.22.0 download, installation and configuration method graphic tutorial

MySQL 8.0.22 download, installation and configura...

Solve the Docker x509 insecure registry problem

After installing Docker, I encountered the x509 p...

Does MySql need to commit?

Whether MySQL needs to commit when performing ope...

How to use Linux whatis command

01. Command Overview The whatis command searches ...

Nginx reverse proxy forwards port 80 requests to 8080

Let's first understand a wave of concepts, wh...

Vue+Element realizes paging effect

This article example shares the specific code of ...