Review the knowledge points before, enhance the use and applicability of knowledge points.

Passing friends, you can click a like, pay attention to ~~~

1. React setState application

SetState is mainly used to modify the state in state. When setState is used to modify the state in state, the data in state will not change immediately, but the original value, mainly because setState is equivalent to an asynchronous operation and cannot be modified immediately.

Common usage

In this mode, modified data cannot be obtained immediately and the operation is asynchronous.

The callback function uses setState to write two arguments, the first to modify the data, and the second argument to a callback function

Instead of receiving an object, setState is used to receive a callback function that takes two arguments, one that takes the previous state value as the first argument and the updated value as the second argument

Note: Since setState can be an asynchronous operation, when multiple updates are made at once, all updates are internally merged into one update, which is merged into the last update.

2. React this pointing problem

React components are mainly divided into two types: stateful components and stateless components. This only appears in stateful components. Stateless components do not have this.

In stateful components (class components), there are three ways to make this refer to the current component

The first kind of

Use the arrow function (no this in it, will look outward — current component)

Note: the arrow function does not have this in it, but looks up one level to find this. If the function is a normal function, the value of this inside is undefine

The second,

You can use an external intervention to bind this manually when a function is called

Note: When you manually bind this using bind, the function can be either an arrow function or a normal function

The third kind of

When called, you can use anonymous functions, which also make this point to the current component

3. Use of ref and refs

Ref and refs are a pair, which can obtain the current component or element label, etc. Ref is responsible for defining data, refs is responsible for obtaining data, there are three ways to use:

Methods a

Name it directly using ref and get it using this.refs. XXX

Way 2

Using the ref function, the principle is: mount the current real DOM to the current component,

Methods three

React creates a ref object, uses it in the DOM object, and then obtains it

Example: