If you feel ok, please like more, encourage me to write more wonderful article 🙏.

If you have any questions, feel free to comment in the comments section


The profile

    1. Component packaging
    • RenderProps enhanced version
    • Web Component
    • The configuration (LCD)
    1. Logic reuse
    • MiddleWare (MiddleWare)
      • Redux Thunk
      • Listen to the history
    • stateComponment

The main purpose of this article is to provide a discussion for framework users (
React/
VUE), and how to proceed reasonably
Component packagingand
Logic reuse.


There is a precondition here — in ordinary times
Business driversHow do we think or how do we deal with it to do it fast and well.


Meanwhile, thanks to my
Develop skill packsfor
ReactSo more I will from
ReactTo think and answer questions.


It’s getting late. It’s time to get down to business. Let’s get our books straight. (Guo Degang voice package) 👈 Click trigger

Component packaging

As a qualified Reacter, component encapsulation is a basic skill that needs to be carved into one’s bones, just like speaking, learning and singing in the mouth of crosstalk performers.

React officially provides us with some common operation methods, including HOC and RenderProps. If you are not familiar with how to use these methods. You can refer to the React component package I wrote earlier. (Maybe the writing style and technique were not very good at that time. If there is something wrong, please spray it gently, I am afraid of pain.) Of course, the current technology is also poor {manual dog head}

But for encapsulation, There are a thousand Hamlets in a thousand people’s eyes. I think the most critical point is that React uses JSX to build UI, which is itself an extension of JS. The biggest characteristic of JS is that everything can be objects, and the flexibility of objects can be said to be everywhere, impossible to guard against.

RenderProps enhanced version

The React website provides a solution for component encapsulation.

Component properties have a property, and that property is a function that returns a component.

<RenderProps renderRegion={(value) = ><CommonConponenet value={value}/>}
Copy the code

This situation can satisfy a large part of the component packaging. But in my opinion, this approach is to separate some of the features that can be removed from the main UI. A programming idea called slice-oriented programming is implemented.

Pumping out reusable components with RenderProps is great, but, but, but, here’s a twist, and I don’t know if you’ve maintained old code or if there’s a requirement. In a main UI, there are many scattered areas of operation, and these scattered areas can be encapsulated. Let’s make a brief description.

Suppose now we inherit the requirements as shown in the figure above, but due to each operation Area, there may be many cases, and at this time, in order to practice the design pattern of single responsibility. Of course, it is not necessarily according to the book’s point of view or rules to do things, and I describe this, just for the division out of the famous (Zhu Di seized the throne also came up with, qing Junside. Recently in reading << Ming Dynasty those things >>, knock nice). We tried to encapsulate each part of it with components.

There is no downside to this approach, except that when instantiating the parent component, it is impossible to see what logic is displayed by the removed component. If the page is simple or there are not many parts to be removed, that’s fine.

However, if there are some extreme cases where the things that need to be pulled out of a component are too fragmented to be merged, there are potential pitfalls in late maintenance.

At the same time, the functionality of some pages is strongly coupled to the structure of the page. Some of you sometimes fall into the trap of encapsulating components for the sake of encapsulating components. Separate the logic that belongs to the same page for separate use into components, and then use various props or other state management to maintain callback and parameters.

When encapsulating components using RenderProps,


1. The removed components are too fragmented to see how the UI is built and assembled.


2. Fall into the trap of splitting logic for the sake of splitting UI

Therefore, in order to solve this seemingly insignificant problem, a variant or upgrade was made based on RenderProps.

Let’s describe the above situation in detail again. Suppose RightBottomArea is a set of buttons, and in the development of the project, several pages have similar functions to the Parent component, but there are differences in the number of displays and operations.

When we designed Parent, we broke up the UI into chunks so that it could be configurable. In general development, we encountered the above requirement, and the first idea was to build a component that maintains the Button (like the LeftTopArea in the first example, etc.) by passing different arguments pageSoucre = pageA or pageB when calling Parent. To distinguish between different pages, and make ternary or multivariate judgments within components.

Now, let’s talk briefly about how I deal with this problem.

Let’s first look at how the component is invoked.

See here, careful friends, the brain may have some questions.

  • 1. How is the button click event bound and is the callback handled asynchronously
  • 2. What should be done if the style of each button needs to be customized

Don’t worry, the dishes are already in the pot, come right away.

Here is a brief explanation of the idea of the API used in this.

  • React.children. map is one use for traversing a component’s Children data and array map.
  • React.cloneElementUsed to copy out a new componentThe type, propsSame as the source component. In addition, the properties of the new component (props)personalizedProcessing.

Conclusion: I do not know whether you have used these apis in the development process, and based on the existing functions of these apis, do powerful applications for their own development.


In fact, the source of this point is mainly from
React.createElement(). It is the man behind JSX, and it returns an object.


It’s and
JS Everything is an object“Fits in nicely. Since it’s an object, as long as we can get an instance of the object, we can
Do whatever you want.


Web Component

This technology is a new way or idea of component encapsulation. It leverages browser apis to give you the ability to encapsulate components.

Web Components is a suite of different technologies allowing you to create
reusable
custom elements– with their functionality
encapsulated away from the rest of your code— And Reveal them in your Web apps!

The above description is extracted from MDN_Web_Components.

From the above description, we can draw several conclusions

  • Build reusable custom elements
  • 2 Separates the built elements from the existing code, using Shadow DOM

Because THE technical solution encapsulated by this component is only briefly used in the actual project, but I feel that this technical solution is the future trend (no matter you use React or Vue framework), so it is necessary to lick my face to tell you about it. (Please feel free to point out any mistakes).

In our project development, we have some kind of presentation effect, which is that the text exceeds the specified width and needs to be displayed… Or a copy needs more than one line.

Normally, we define a class in a div or span

And then we useJSXLet’s just show you how it works.

Although we have reduced the amount of code by customizing CSS properties, functionality like this is common in a system. Write the corresponding style for each use (of course, you can maintain this style globally) and reference it in the specified component or element. Increases the maintenance cost imperceptibly. Of course, some of you might think of building components out of such pieces that are ancillary or presentation functions and not very well coupled to the business.

The thinking is correct, but every time you need to use such a piece of functionality, you need to import the component into the object file. If there are many similar components, there are many related component imports in the header of the component. There are potential problems with this,

  1. If the feature piece component path changes, the place to introduce it also needs to change (high maintenance costs)
  2. Some feature pieces are very large and not doneAccording to the need to load, the page will load slowly for the first time (Loading speed )
  3. In the header of the calling function component, the code is bloated. (not beautiful)
  4. Removed component that may conflict with original component style (conflict exists)
  5. Unable to cross frames (Vue/React)
  6. .

So if we followWeb_ComponentsLet’s refactor that code.throughextends HTMLElementThe related attributes are then inherited.

We can talk about custom element instantiation in the same way as reference components.

This is a good idea, but could we think of a different way to instantiate elements in a slightly top-level directory or component of our project, so that it is instantiated once and called everywhere? It saves a lot of effort.

Although not much has been done in real projects, both Vue and React are now trying to move in the direction of Web Components.


The configuration (LCD)

Low-code Development (LCD) is a Development mode that has been proposed for a long time (2011). Developers mainly use graphical user interfaces and
configurationTo create applications, rather than relying on handwritten code as the traditional model does. One of them is based on writing
JSONLow code development.

This approach is not strictly LCD, but we can use this idea to encapsulate components.

Those of you who have done ToB business know that when we do form queries, there are always strange filters, and these filters are sometimes simpleInputOr is itSelectTo get a little more complicated, add some custom components that you encapsulate during filtering.

Let’s simply plan the above filtering part according to Antd components.We handle this logic in the normal way, with more than three event callbacks (basically one for each component) before it is fully written, and some similar functionality as wellRepeat rateIs very high. So blindly goPiled upThe code, then, is a query related code will changelong. It was a pain for me and the people who were going to take over the maintenance of this code,

So how can we be moreelegantOr make the code look betterconciseWell, I’m going to mimic the LCD implementation. Describe it briefly.So even though you’re seeing this LCD way of handling code, the amount of code is increasing on the surface, but there’s a prerequisite for that. As described in the figure above, if there are more than 8 criteria in a filter box, you need to write the corresponding callback and configuration information, and these configuration information are in factsimilar. And the code is hard to track. Let’s do a simple conversion. We built filters in the most primitive way. We built five components with over 50 lines of code, and that’s when some components didn’t have the necessary parameters and callbacks configured. Implement a filter with more than 10 filters and multiple custom components, starting with at least 300-400 lines of code.

And we use LCD thinking to do code, which is at most 200 lines. It’s a 50% direct savings on the amount of code, which is conservative.

You can take a look at writing this kind of code, you can compare the amount of code. You’ll see it all at once.

Just to give you a little bit of a sense of how I decouple and encapsulate this code.

  • 1 Uses the event broker supported by the React function to mount processing events to parent elements. (React actually does the same thing.)
  • 2 For custom components, we pass the configuration information ininstanceReact JSX is itself an extension of the JS syntaxEverything is an object
  • 3 uses custom attributes to transfer data

Logic reuse

Component encapsulation is one type of logic reuse, but I would like to talk about data/logic processing in addition to component encapsulation separately, because some ideas and methods are described and thought about from a different perspective.

MiddleWare (MiddleWare)

You have been exposed to the development of Experss Node, which is full of various middleware. I see the role of middleware as a front-end implementation of slice programming in front of you.

Instead of talking about Node, we’ll focus on the front end of the page. If people use React and the project is bloated, they only use context and state provided by React to maintain the direct data of the page, which will become chaotic. So Redux was born out of nowhere.

We won’t cover how to configure and use Redux, but I’m sure there are plenty of books out there. We will discuss how to use Redux for logical extraction and reuse.

Case 1: Redux-Thunk

In project development, we hope that when the interface is triggered to send, there will be a front-end Loading effect processing, and then when the interface request succeeds or fails, the Loading will be removed. (We can also intercept with Axios)

A word of redux-thunk, just a few lines of code, serves as Redux’s asynchronous processing middleware for handling asynchronous actions. Realize the function of reverse of control.

Since we’re dealing with asynchrony, maybe we can do something here. If the asynchronous action were a promise, we would handle some of the loading logic.

There is a prerequisite for the initiation of interface processing that needs to be wrapped with Dispatch.

  • 1 We set loading in store to true when an asynchronous operation is triggered
  • 2 After an interface fails or succeeds, set loading in store to false
  • 3. At the same time, a global Loading component is used to listen to Loading in store to display corresponding operations

Case 2: Listen for history

In actual business, some operations need to detect the change or occurrence of the specified URL and need to do some additional operations. For example, for certain pages, resources on that page need to be locked. In SPA scenarios, one URL corresponds to one resource.

So, we can do the specified operation by listening for changes in History.

We can do some interaction with the background by listening to objectId and isTriggerLock in the store from somewhere. The good thing about this is that

  • 1. By means of middleware, the logic is removed to the framework level, and the degree of coupling with business code is not so high
  • 2 If a page or module needs such functions in the future, the migration effect is good (adding configuration items is ok)

There’s another important point here, which isto receive a history, and that history is instantiated through the history library createBrowserHistory. So you can listen on @@router/LOCATION_CHANGE. (This is a gadget I stumbled upon by reading the source code)


stateComponment

The term stateComponment is a coinage of my own, and what it means or uses – is to store a component in a component’s state variable. Through setState to switch the component pointing, so as to achieve the transformation of the page.

Let’s just describe it briefly, just to give you a simple idea.

Suppose we have a number of operations on the page, and those operations correspond to a Modal. In our normal code, we basically write a button -> visible -> Modal

In fact, in my opinion, the visible variable is a drag, and if there are multiple modal, it also needs some extra parameters to maintain. So if we simplify things, by storing components in state, will it be more convenient?

This is a very common example where you can replace Modal with another custom component or element.

In fact, I want to use this example to illustrate that in React project development, a component is actually an object, while everything in JS is an object, and its flexibility is very high. We don’t have to stick to the usual way of using components. We’ll just handle the component the way we write JS variables


In fact, there is one thing about logic reuse that is hard to get around: custom Hooks. However, if I simply talk about it, I always feel that I cannot explain it thoroughly. Therefore, I plan to write a special article about my opinions and views on custom Hook.

Well, it’s getting late. It’s 2 o ‘clock in the morning, and the liver isn’t moving. Today is the last day of 2020. I hope everyone will leave their unhappiness in 2020 and bring happiness to 2021.

I wish you all a happy New Year

Double click, touch.