A journey to explore the react self-built inner structure
In previous articles we covered the fundamentals of react and how to build more complex interactive components (Basic tutorial qkxue.net). In this article we will continue to explore the features of react components, especially the life cycle.
Thinking a little bit about what the react component does, the first thing that comes to mind is that react describes how to render (DOM). We already know that react uses the render () method to achieve this goal. However, only the render () method may not necessarily meet our needs. What if we need to do something extra before or after the component rendered? What do we need to do to avoid repeating rendering (re-render)?
It seems that we need to control the various stages of the component (run), all the phases involved in the component's operation are called the component's life cycle, and each react component undergoes these stages (Tengyun technology ty300.com). React provides methods and notifies us when a component is in the appropriate phase. These methods are called life cycle methods of the react component and are called in a specific and predictable order.
Basically, all react component life cycle methods can be divided into four phases: initialization, mount phase (mounting), update phase, unload phase (unmounting). Let's take a closer look at each stage.
Initialization phase
The initialization phase is the phase in which we define THIS.PROPS defaults and this.state initial values, respectively, through the Getdefaultprops () and Getinitialstate () methods.
The Getdefaultprops () method is called once and is cached-shared among multiple instances of the class. Before any instances of the component are created, we (the code logic) cannot rely on the this.props here. This method returns an object and the property is attached to the This.props object if it is not passed in by the parent component.
The Getinitialstate () method is only called once, just before the mounting phase begins. The return value will be treated as an initial value of this.state and must be an object.
Now let's prove the above conjecture that implementing a display value can be increased and reduced by the component, which is basically a counter with "+" and "-" buttons.
The life cycle of React components