Data is needed in many places in React, which is called state in React. We need a special method to manage state, so state-related methods were born. State should be required to have two basic functions: first, it can store certain values so that it can be used by react, and second, it can be monitored by react and re-rendered when it changes. Here we introduce how to write state in class and function components respectively: Class Componentclass ClassComponent extends React.Component{ constructor(props){ super(props) } //Optional render(){ return ( //You can write jsx syntax here) } } We generally use setState to change the state. We can directly pass an object to be changed or a callback function. Note that if an object is passed in, React only makes a shallow copy, not a deep copy. Therefore, if other objects in the object are changed, React cannot know to render. This method essentially passes in a new value and overwrites the original value. If this value is the same as the original value, React will not render.
The constructor in the class component can be written or not. There are two main functions of writing this constructor:
constructor(props){ super(props) this.state = {n:12} } render(){ return ( <div> <h1>THE TIME IS {this.state.n}</h1> </div> ) } Note that setState cannot be written here. The above method React can also be set externally, that is, state = {n:12} render(){ return ( <div> <h1>THE TIME IS {this.state.n}</h1> </div> ) }
constructor(props){ super(props) this.addNum = function(){fn()}.bind(this) } render(){ return ( <button onClick={this.addNum}>+1</button> ) } However, this method has been replaced by a new method in React. The code is as follows: addNum = ()=>{ fn() } render(){ return ( <button onClick={this.addNum}>+1</button> ) } Therefore, there is no need to write the above constructor to inherit the parent class method. Functional Componentsimport { useState } from "react" function FunctionComponent(){ const [data,setData] = useState("the initial value you want to pass in") return ( <div>SHOW DATA {state}</div> ) } The function of setData here is similar to setState, but it can only be used to change the state of data, and a callback function is passed in when it needs to be changed. The function takes as its argument the previous value and returns the value to be changed. The essence of this method is to pass in a new object to change the value of the previous React object. For this purpose, you can also simply write the changed value directly. By default, it will correspond to the current object and change its value. The above method is much simpler than the original setState, but the trouble is that if there are multiple data, you need to useState multiple times and cannot pass in multiple values at one time. However, in most cases, data management issues are managed by Redux, so React itself does not need to worry about it. The pitfalls of setStateWhen changing the state of a React component, a common problem is the value merging of setState. Look at the following questions: this.addNum = function () { this.setState({num:this.state.num+1}) this.setState({num:this.state.num+1}) this.setState({num:this.state.num+1}) }.bind(this) At this time, when the addNum function is triggered, num is only increased by 1. It didn't add 3 as we thought. React itself explains this: Calling setState is asynchronous - don't expect this.state to be immediately mapped to the new value after calling setState. The explanation for this is:
Simply put, when React is executed, in order to improve performance, the setState to be updated will be stored in an array. When the synchronous code of React itself is executed, before the update, the setState in the array will be taken out and then rendered. In the above code, because we added the synchronous code this.setState({num:this.state.num+1}) to setState, when batch processing is taken out, a merge will occur, merging many setStates into one sentence, thus only changing 1. Because of this mechanism, setState looks like asynchronous code, but it is actually executed synchronously. At this time, if we change the previous synchronous code to asynchronous, we will get the result we want. this.addNum = function () { setTimeout(()=>{ this.setState({num:this.state.num+1}) },0) setTimeout(()=>{ this.setState({num:this.state.num+1}) },0) setTimeout(()=>{ this.setState({num:this.state.num+1}) },0) }.bind(this) At this point, the value is directly increased by 3, because the asynchronous code will be temporarily stored while the code is executed. It is executed after all synchronous codes are executed. At this time, the batch processing mechanism has ended, so all three functions are executed, so 3 is added. This is what I can think of so far. If there are new ones in the future, they will be added. The above is the detailed content of the detailed explanation of the use of state, one of the three major attributes of React. For more information about the state, one of the three major attributes of React, please pay attention to other related articles on 123WORDPRESS.COM! You may also be interested in:
|
<<: Solution to 1449 and 1045 exceptions when connecting to MySQL
>>: How to use Volume to transfer files between host and Docker container
!DOCTYPE Specifies the Document Type Definition (...
The <label> tag defines a label (tag) for an...
1. To build a PPTP VPN, you need to open port 172...
Table of contents Overview in operator refinement...
Start a new project This article mainly records t...
By default, the table title is horizontally cente...
1. Basic structure of web page: XML/HTML CodeCopy...
<br />A contradiction arises. In small works...
Table of contents 1. Introduction 2. Ideas Two wa...
Preface After a long time of reading various mate...
Background-image is probably one of those CSS pro...
As shown in the following figure: If the version ...
<br />Introduction: This idea came to me whe...
Table of contents Preface No.1 A focus No.2 Extra...
The decompressed version of mysql5.7.18 starts th...