React uses hooks to implement two-way data binding
Write it first: Before reading the use of hooks, you need to have a certain understanding of the Class implementation method. Let’s start with this:
const root = (('root')); function tick() { const element = ( <div> <h1>Hello, world!</h1> <h2>It is {new Date().toLocaleTimeString()}.</h2> </div> ); (element);} setInterval(tick, 1000);
In the early stage of react, we learned to use ReactDOM to mount elements, use jsx mode to edit and visualize stronger (<html />, and implement function calls through setInterval; how to use Class to write more standardized and editable code?
The following steps are available in the React official documentation:
- Create a eponymousES6 class, and inherited from
。
- Add an empty one
render()
method. - Move the function body to
render()
Among the methods. - exist
render()
Use in the methodReplace
props
。 - Delete the remaining empty function declarations.
First of all, applying Class is an indispensable strategy in my opinion, because the original js editing mode and the introduction of react, the way of mounting using react DOM is too primitive, and lacks scope division, lacks reusability, and even becomes very passive when you want to implement one more function.
class Clock extends { render() { return ( <div> <h1>Hello, world!</h1> <h2>It is {()}.</h2> </div> ); } } function tick() { ( <Clock date={new Date()} />, ('root') ); } setInterval(tick, 1000);
Even if we are not familiar with Java enough, we are not clear about the underlying principles of classes and inheritance in js, but intuitively, the emergence of class quickly reminds us of a word, that is, "object-oriented".
As we all know, JS is not an object-oriented son, but is more object-oriented through new contributions in the later stage of development. As an engineer in developing programs, especially a novice who has just met "JS", use is better than understanding, because only practice is the only way to master theory.
Next, we use a piece of code with the same effect to talk about the problem of Class and the use of hooks:
import React, { useState } from 'react'; function Example() { // Declare a state variable called "count" const [count, setCount] = useState(0); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); }
class Example extends { constructor(props) { super(props); = { count: 0 }; } render() { return ( <div> <p>You clicked {} times</p> <button onClick={() => ({ count: + 1 })}> Click me </button> </div> ); } }
Admittedly, the reduction in the number of lines of code can make us appear more professional and advanced, and the declaration of function seems to be more streamlined than class extends, but it is really worth noting that:
About this:
Friends who have experience in front-end interviews know that improper use of this is a bad thing. If you want to learn this well, you can go to the Nuggets to brush up the classic front-end interview questions, or open Chrome F12 when you are fine to try it. However, in all scenarios where you have not understood this principle thoroughly, or you are simply a cautious program developer, then avoiding using this in some places where errors may occur will be a good choice. The biggest advantages of Hook operation are shown in this way: students who are more familiar with the function writing method, avoiding the inaccurate pointing of this in each layer call, which leads to the occurrence of bugs; in addition, the binding method of count and setCount is used to separate the state and action layers, and const prevents variable pollution. The above are the advantages of hooks I want to share. Next, I will introduce the use of hooks: useState, useEffect.
(New content)
About useState
Based on the above content, we have already understood the way to declare hooks:
const [count, setCount] = useState(0); // 0It is the initial value
Let's start with this statement. Const is the way to declare an unchangeable quantity in ES6. We can clearly get the literal meaning of "you can't directly modify the value of count in the program". [ ] just ignore the form. count and setCount are defined by ourselves. We are used to adding the name of set as its modification method. UseState fixed writing method, (0) is the initial value, and can be passed into various types of objects with practical significance in js, such as object {} array[] time new Date or a simple null.
About the set method
What are the questions that students who are in contact with the first time? How to use the modification method? It is very simple. In the same context, directly use setCount(*new value*), "that context..." to convert it into vernacular: the component can be used directly at present, and the value declared by useState is regarded as a private variable of the current component. If it needs to be used elsewhere, please learn how to pass the value (this is another topic, and it may also be updated to subsequent articles in the next period of time);
After learning this, we probably think this method is great and will not be polluted. It is available for your own private domain, and can be bound to the DOM, etc. I remember that at the beginning we said it was two-way binding. The set method should have a get corresponding to it. So what is the use of hooks?
Asynchronous and side effects:
First, let’s take a look at a not-so-simple code:
const [count, setCount] = useState(0); setCount(1); (count); // Console output:0
If you are interested in learning, you must know that this is the asynchronousness of the setCount method. The explanation given by the official document is: "useState may be an asynchronous operation". It may not be important to understand it. We cannot put the program in possibility. So the official provides the brother method of useState: useEffect.
About useEffect
const [count, setCount] = useState(0); setCount(1); (count); // Console output: 0 useEffect(() => { (count); // Console output: 1 });
This code will not be explained, let’s talk about it:
Students who are familiar with vue should apply computed and watch attributes during the development process, so that the page data remains "real and correct". In many cases, a button will cause multiple display items to be refreshed, and delays are what we should avoid. UseEffect is such a method. It will start listening within react. When an object changes, the response function will be triggered. In this function, we can use the set method declared by useState above to change a data item bound to the page to render a new page.
Raise your hand: What's going on with the "some object" you just mentioned?
Please see this code:
useEffect(() => { = `You clicked ${count} times`; }, [count]); // Only in count Update when changes
OK, when you read this position, you already have quite in-depth "introduction" knowledge. You can choose to create a new react project, output a few items of content, bind one or two data, and practice to produce true knowledge.
Then look at the code, we usually use useEffect (function(), props); to bind the monitor object of useEffect. In the above example, if the value of count changes (by any reason), the header modification statement will be followed.
OK, so since props are an array, can we pass in multiple monitoring sources? No.
Can the use Effect method solve the asynchronous problem of useState? Yes.
Can I use the Effect method to declare periodic functions? Yes, we fill in the blanks of props, that is, [], and will make a call once and only once at the beginning of component creation, similar to the created declaration cycle hook in Vue.
Is the useEffect method asynchronous? It doesn't matter, because the page will update with the statement in useEffect.
What is the implementation of useEffect? useEffect Because it can monitor multiple data sources, there will be multiple use Effect functions in a component, and they will be treated as a whole, that is, a method tree. Each new method will be mounted on it. After the change occurs, the entire tree will be refreshed and changed according to the DOM tree.
Additional information about Hook
Don't call Hook in loops, conditions, or nested functions,Make sure they are always called at the top of your React function and before any return.
By following this rule, you can make sure that the Hook is called in the same order in every render.
This allows React to be able touseState
anduseEffect
Keep hook state correct between calls. (If you're curious about this, we'll have a more in-depth explanation below.)
Don't use Hooks in non-react code.
Summarize
(The above content is similar to the examination instructions, please understand it yourself)
The above is personal experience. I hope you can give you a reference and I hope you can support me more.