React Component

props
The React elements
JavaScript function

Class Component

React createClass

There are two ways to create a Class component. Here is an example of how to create a Class component in React.

Writing instructions:
  1. propTypesPropTypes are used to handle type validations to validate defined attributes. They were taken from React, deprecated after React16.0.0, and extracted separatelyprop-typesPackage, so first compare the new version, we need to perform type verification, need to manually introduce the module prop types
  2. getInitialStateTo initialize state,getDefaultPropsFunctions are used to define the default properties for props, similar to the data and props methods in vUE today
  3. The createClass component needs to define oneRender functionIt returns the React Node for rendering the view
The ES6 class the react

This is a common ES6 class React component

Writing instructions:
  1. The React inv0.13.0The introduction of theComponent APIWith some transcoding tools we can use the latest ES syntax
  2. The component also needs to define oneRender functionUsed to render views, es6 supports method shorthand, render and other defined functions no longer need to declare the function keyword
  3. State is initialized in the constructor, and you can see one heresuperES6 specifies that the constructor of a subclass must execute the super method once. If the subclass does not define a constructor method, the constructor is added by default and calls super. If we declare the constructor function, we must call super in the constructor. This object can be accessed only after calling the super(props) method normally. To access this. It can also be accessed directly through props. But whether or not constructor is defined and super is passed as props, this. Props can be used in any other lifecycle of React, which comes automatically with React.
  4. React doesn’t automatically bind this. In order to access this properly, we need to bind this Pointers in the constructor. However, if there are many methods, there is a lot of redundant binding function code in the periodic constructor
The elegant solution of the function this

Class field syntax
Field name = reference value

Field name = state
this

React.PureComponent

PureComponent inherits react.component. shouldComponentUpdate (shouldComponentUpdate) The react. PureComponent uses shallowEqual internally for shallow comparisons. A shallow comparison is performed to check whether the length of the props and the state before and after the update is the same, and determine whether the number of data of the props or state is added or reduced. The objectis method is similar to the object-is method in ES6. Object-is is similar to the === congruent operator, but does not behave the same when comparing +0 and -0. === = returns true and it is false.

Functional Component

  • Function components have no life cycle
  • It has no internal state of its own
  • Because it is just a function, there is no internal this when called

Here is a simple example of a function component. Although the function component is essentially a JavaScript function, it doesn’t appear to have any react apis or methods. However, we still introduce react because the React element returned inside the component uses JSX. This is essentially the syntax sugar for react. createElement. Babel can be configured to compile JSX for us, simplifying the process of writing createElement.

Stateless Component

Difference between Class and Functional

Function components do not need to declare classes, which avoids a lot of code such as extends or constructor and does not need to deal with the problem this points to. More purely, a function is a component. The React component has always been more like a function, and we wrote functional components closer to the React principle. Reference transparency is a concept of functional programming, and I personally feel that functional components follow the concept of pure functions.

Pure functions

Reference transparency is a concept in functional programming. This is a Reducer function in redux. Reducer needs are defined as a pure function in Redux, which conforms to several definitions of pure function:

  1. The same input will always have the same output
  2. Reducer does not modify the state and only returns a new state
  3. Independent of the state of the external environment
  4. No side effects

React Hook

Most of the time when we start writing simple code or components, we may choose a function component to complete a simple function module. However, as the function becomes more complex, it may need some state or life cycle of its own within the function component. In order to achieve these functions, it may need to use high-level components or render props to wrap a layer of the parent component of the class, so that it indirectly owns the state and life cycle. But this is all about leveraging the capabilities of the class component outside of the function component.

Since a function component is re-executed from top to bottom every time it is rendered, it has no way to have its own internal state and no side effects, so hooks are created to enhance the function component.

Vue Hook

Vue is releasing the possible 3.0 update. The picture above shows the funtion Based API with big changes.

In contrast to the 2.0 notation on the right, template is the previous template syntax. A special one is the setup function. Value is a wrapper object, which is the internal state of the component. This looks very similar to usEstate Hook in React. OnMounted returns an object similar to data, which is bound to template syntax. Setup looks like a simple function.

function based api
react hook
typescript

React Hook

16.8 the React
class
state

We see the use of a useState API, which can pass in arguments and return an array when called. An array contains two items, the first is the state and the second is the setState. Using the es6 array destruct feature, we can de-semantically name it as we want. The init parameter in useState will only be used after the method is initialized for the first time, even if the function component is updated. Its state is also not reset, so it can always remain in its current state. This gives function components their internal state, as well as their life cycle.

Some hook usage and points to note

Hook skips state update

In the React class component, we define the state of an array type. After modifying some values in the data reference, calling this.setState will trigger a re-rendering, but the same operation will not trigger an update in the hook.

UseEffect introduction

UseEffect rules are as follows:

  1. When the second does not exist, the callback is triggered after the first initialization and each rerender.
  2. While the array is present and has values, if any value in the array changes, the callback will be triggered after each render.
  3. When it’s an empty array, the callback is only fired once, similar to componentDidMount.
  4. Each useEffect can return a cleanup function.

Hooks Rules

Why do Hooks need to follow rules

  • MemoizedState: Stored status value after the last full update queue execution
  • BaseState: initialState value initialized and newState updated after each call to setter to trigger Dispatch
  • BaseUpdate: Indicates the current Update
  • Queue: The update Queue of the current hook, which stores multiple updates to which we will be pushed every time our setter dispatches

useState hook

React creates corresponding hook nodes. When React initializes components for the first time, it connects these nodes to next and dispach the corresponding action method every time setter is called. Store actions in a queue.

When we do a subsequent render, React calls the contents of the queue, which is also a linked list structure that collects when we call the setter methods, the queue in turn performs internal actions to get the latest state value, The state value is updated to the memorizedState, which is then bound to the corresponding hook field. So when we scramble or add or remove hooks, we get the internal order of the hooks out of order and they don’t work properly.

Above is a single linked list of hooks that use next to point to the next hook.

Try to modify the number of hooks. We called three USEstate hooks during the first initialization, and React will collect three hooks in sequence. The first time we render, the page can render content normally, when we click on a setter method to trigger the rendering again, the number of hooks will be less than before, resulting in page errors, unable to render normally. So ensure that the same call order each time to use the hook correctly.

Hook life cycle

The Constructor:

ComponentDidMount: When the second argument is an empty array, the callback is fired only once, similar to componentDidMount.

ComponentDidUpdate:

UseRef returns a mutable ref object that can be used not only to bind references to the DOM, but also to store values. Its.current property is initialized as the passed parameter. The returned object lasts for the lifetime of the component. Changing the.current property does not cause component rerendering.

ComponentWillUnmount Previously mentioned that each useEffect can return a cleanup function. With this feature, we can still set the second argument to an empty array, so that the cleanup function will be called before the component is unloaded, and we can clear some event listeners in it, etc. More conveniently, we can write didMount and unMount in the same useEffect hook.

ComponentWillReceiveProp:

The second argument to setState We know that when we use the setState method, we can pass in the second argument, which is a callback function that will be called after the state is set. We can also use the useEffect hook to pass in the state we want to listen to. When the state is updated, the callback will be called.

Logic reuse

Customize the Hook

React allows custom hooks to be defined using the use prefix. A custom hook is not a component and does not need to return a React Node element. If it does, it becomes a function component. It can also usestate usestate and lifecycle useeffect and other hooks inside methods. He has his own internal state and life cycle.

You can simply return a value, an object, an array, or even a method, depending on the properties you need to call the custom hook you created.

Instructions:

Here we define a custom hook called useOnline, which we use to determine the current state of the network connection. First, hook method names start with use, and the following names can be defined as you wish. Most of the time hooks follow the hump nomenclature, as long as they start with use, there is no limit to the definition. However, I tried to create custom hooks that worked even without the use prefix. The React convention starts with use in order to use some automatic check tools to check whether the use of these hooks violates the rules of using hooks. However, it is best to follow a convention that starts with use and names the hump.

Then call usEstate to create a state inside the custom hook, pass in navigator Online to initialize the current network state, and have their own state inside the custom hook.

Then, using the UseEffect hook, we need to listen for changes in network state. The connection or outage listener method only needs to be called once when the component is created, so we pass the useEffect second argument only an empty array, so that it will only be called once during didmount.

We also need to clear up these listening events when we destroy the component. You can simply clean up the two listener methods in the effect hook return function

Finally, we use the current state value as the return value of the custom hook, thus completing a custom hook that listens to the network state.

Call useOnline to customize a hook

We introduce this hook in one of the simplest function components. Then within the function component we call this custom hook, which returns the current network state. This is a very simple function component, we only render the current network state.

When we render the component it renders the current network state. When we switch to offline state, we can see that the component is re-rendered to the current network state value. In this way, when we create a custom hook, we can call the direct reuse of this code in many places, to achieve the purpose of logical reuse.

But you might think isn’t that just abstracting a method? We can also abstract some methods into some utility functions and write some helper or utils to accomplish these functions. The power of a custom hook is that it has state. When the state value changes, it can trigger the re-rendering of the calling component. Moreover, the custom hook can follow the life cycle of the component.

Custom lifecycle hooks

We can choose to implement a useDidMount custom hook ourselves, which is very simple to implement. Just call useEffect Hook inside the hook, pass its first argument to our custom hook callback, and set the second optional argument to an empty array, so it will only be called once in didmount.

Custom hooks in the open source community

This open source project helps us collect a series of custom hooks that are already packaged, such as these lifecycle hooks, which we just need to introduce to implement. Include didMount, unmount, Update, etc.

React Hook Progress bar component

React Hook Act-Arc-Progress is an es6 plugin for installing the React Hook act-Arc-Progress.

  1. Use only react version >= 16.8.0 because it uses the React hooks API
  2. With typescript, components are automatically prompted for type derivation of arguments and methods if ts is also used
  3. Source code using TSLint and the Airbnb specification for line code style verification

There’s no point in building a wheel over and over again, so add some unique features to make it even more different:

  • Most hoop bars are a full circle. This component can be curved and can define its start and end positions freely.
  • You can pass in a number that automatically increases as the progress bar grows.
  • One or more literal nodes can be passed in
  • You can define the thickness of the progress bar so that the inner layer exceeds the outer layer
  • Progress bar background can be textured
  • The animation speed can be adjusted by a speed threshold, or the animation duration can be fixed

GitHub address, please give a star bar ◔ ‸◔