This article has been published by authorized NetEase Cloud community by the author Huang Kai.

Welcome to visit NetEase Cloud Community to learn more about NetEase’s technical product operation experience.


Component design, from a simple point of view, is how to improve the efficiency of coding, improve the rate of reuse of code method, from a high level of view, it is an art of programming

It was nice to read redux author Dan Abramov’s Presentational and Container Components recently and see a lot of people talking about component patterns. As someone who’s been scratching his head thinking about how to structure code every time he writes a requirement, How best to use design and use components at work is really an issue worth discussing.

Note: The images in this article refer to Michael Chan’s talk on React Component Patterns: React Component Patterns.

preface

Portfolio model

First, let’s talk about components from a macro perspective.

Now a lot of people are talking about design patterns, design patterns. What are design patterns? Design Patterns mainly refer to the GoF (Group of Four). The book Design Patterns proposes 23 design patterns that are widely used in software engineering and represent best practices. Among these patterns, there is a design pattern called Composite Pattern. According to Wikipedia:

The purpose of the composition pattern is to group objects into a tree structure to represent a part-whole hierarchy.

The composite pattern makes the use of single objects and composite objects consistent.

It has the following advantages

  • Scalability: Because components are sufficiently decoupled, you can easily update and replace components

  • Coding efficiently: By breaking down functionality, you can focus on the implementation of each sub-module’s functionality.

Composition patterns in javascript — components

If you use frameworks in your current work, you will find that most of them use the composite design pattern. Vue and React Components, for example, allow you to write small Components and then build your actual application from their combination.

In school, the teacher always said, to have a big picture, big picture. Using combination patterns is a great way to exercise your big picture perspective. Here I think yunqian senior said very appropriate:

Remember, the first step to receiving a requirement is never to write code, but to figure out what you’re going to do and design the whole thing in God mode.

Open god’s eyes

Let’s play god in our programming world and see what’s going on in our world of components.

Component birth

In the language of the framework classes, the component is the basic unit of our actions, React to the operation of the component provides many useful API, a component is using these apis, has a strong vitality, you can see it as a functional cells or individuals, all of our APP is composed of the individual cells (individual).

Then, as you’ll see in everyday use, some components always use one part of the API, and some components often use another part of the API. That these components are starting to think of themselves, creating differentiation (think of it as a genetic mutation). As these differences become more and more numerous, we find that the components are subtracted into different camps due to their respective capability preferences:

There is a lot of talk about grouping components:

  • Fat and Skinny components

  • Stateful and Stateless/pure components

  • Smart and Dumb components

  • Container and Presentational components…

They are all essentially the same, and here we use Redux author Dan Abramov’s term for Components, containers and presentation Components, using Container and Components

Components are divided into camps, it is necessary to start to develop standards, the so-called no rules, no square, a good organization to determine their unified flag, core values, to facilitate the follow-up to find more similar people, development and growth.

Component alignment

Container component camp

They call themselves rulers, and this is a gathering of elites who are used to governing and organizing. As a superior manager, he will never do anything he can ask his subordinates to do.

So they developed a set of criteria that matched their values:

  • I only care

    How do things work

    And don’t care what it is

    How to behave

    .

  • No styles: I have almost no labels except for a few wrapped divs, and I never have any styles

  • Stateless: I hold the core data and you do the rest

  • Usually generated by other components: We usually represent higher intelligence (generally generated by higher components)

  • Representative: various Page pages, routing pages

Show the Components camp

They are usually composed of blue and white collars, representing the vast working class, and they do all the dirty work. They usually don’t have much idea, but simply want to do their own work well and take less responsibility.

Here, each component cares little and their ambition is to do the essential job well, so they have developed a set of standards that fit their work habits:

  • Is for rendering: focus

    The appearance of something

    .

  • Styling: Basically, this is where all the dirty work of dom rendering and styling is done.

  • Emphasize independence (important) : We have a clear division of labor and are not dependent on the rest of the application (such as Flux operations or stores).

  • Don’t care about data: We don’t care about how data is generated, so don’t specify how data is loaded or changed in our place.

  • Receive back instructions: Receive data and callbacks only through props.

  • Weak state: We hardly need to have our own state (when we do, it is UI state and not data).

  • Representatives: Search, SiderBar, UserList, Pagintation

The two camps are basically completely independent, and because of this fine division, they can get along well in society (blue is the display component, gray is the container component).

Actual operation

Well, look at their rapid division of the camp, we have to give them something to do, to see how this social division of labor actually works.

By the way, React component definitions usually come in two ways: class and stateless function definitions

Stateless function definition:

The advantage of this is that it is independent and has no state. It can only modify its props according to the input. This component has good versatility and is easy to modify without affecting other components.

var User = ({name}) => (  <span>
    {name}  </span>);Copy the code

The class definition:

If there are built-in states that need to be maintained, or you need to use a lifecycle, you can use a class-defined approach.

class User extends Component {
  constructor(props) {
    super(props);    this.state = {
      name: props.name,
      editable: false}; }render() {return. }}Copy the code

Container components – define structure and issue instructions

Container components can be defined by a class because lifecycle hooks may be used (or may not be used with DVA).

If a Redux-like state management mechanism is used, it is typically generated by CONNECT (Relay’s

CreateContainer ()
The Container. The create ()

Now we’re going to make a user page, and we’re going to assign this task down, and one of the container camp gets this page creation metric, and then these guys start doing organizational work, and they think they need to build three components to do this: UserSearch, UserList, and UserModal. Then the instructions (data) that each component needs to handle are written and put in userXXXProps. Ok, they’re done, and go to the people in the container camp to implement those functions.

functionUsers({Users}) {const {loading, list, total, current,} = Users; // Deliver the task const userSearchProps = {}; const userListProps = {}; const userModalProps = {}; // Overall structure designreturn( <div> <UserSearch {... userSearchProps} /> <UserList {... userListProps} /> <UserModal {... userModalProps} /> </div> ); } // Specify subscription data, where users is associatedfunction mapStateToProps({ users }) {
  return{ users }; } // Create a data associationexport default connect(mapStateToProps)(Users);Copy the code

Display container – receive instructions and start

In general, stateless function generation is recommended for presentation containers

A good presentation container should be independent of each other, which is what a good division of labor society should have, so stateless functions are usually used to generate a component. In this case, you usually do something (whatever the boss wants you to do) based on the values passed in for props.

Const UserList = ({total, current, loading, dataSource,}) => {const columns = [...] ; // Get to work building a rendering of the componentreturn (  <div>
    <Table
      columns={columns}
      dataSource={dataSource}
      loading={loading}
    />
  </div>);
}Copy the code

So this division of labor seems to be working pretty well. So is this the whole picture of society? Of course not. In real life, component differentiation can be more precise and refined.

For example, some component design patterns subdivide component patterns into:

  • Proxy component

  • Presentational component

  • Layout component

  • Container component

  • Higher-order Component (HOC’s)

  • Render callback

However, I personally believe that the above two divisions are enough to deal with most situations in life, and the mixed Component can be achieved through the combination of the two.

conclusion

In this way, the social division of labor seems to work well, and in fact, it is a summary of the experience of many developers.

But many people see this division of labor as their dogma for designing components, which is bad because there are always exceptions, and maybe in some complex business scenarios, Container and Components need to be mixed. You need to be flexible with it, which is why Dan modified his article:

I amended the article because people were taking the separation as a dogma. 90% of React users don’t ever plan to have something like a living styleguide. There is no need to make life harder for them. Even those that do, Don ‘t need to make

every

What suits you is the best.

Why make life harder?

Finally, what are some good application development steps? I think it might be:

  1. Figure out exactly what you’re going to do

  2. Division of functions

  3. Organize the directory structure by function

  4. Design your data model

  5. Design your container and determine the overall frame structure

  6. Start filling the presentation container in turn

  7. Connect components to data models

  8. test

reference

Composite pattern

React component patterns

React Patterns

Presentational and Container Components

Container Components

React.js Conf 2015 – Making your app fast with high-performance components

Components and Props

Guide to Using the Composite Pattern with JavaScript

Dva quick start


Free experience cloud security (EASY Shield) content security, verification code and other services

For more information about NetEase’s technology, products and operating experience, please click here.



[翻译]pytest testing framework (part 1)