“Live up to the time, the creation of non-stop, this article is participating in 2021 year-end summary essay competition”

In November 2020, I left Guangzhou for 5 years and came to my current company in Shenzhen. At that time, there were about 15 people in the front end team, but unexpectedly, by March 2021, 9 old colleagues had left, including my mentor and the front end supervisor. Especially on the day when the supervisor left, I felt a little depressed, because the ceiling of the team was largely in the Leader. At that time, I thought that job-hopping was to find a good leader and a good team to learn more skills, but I never expected that the reality was like this. But bam, pretty soon, by the end of the night, I adjusted my mindset. Now that the ceiling has gone, LET’s try to improve the technical ceiling of the team.

This is a chat with a friend that day

Technical aspects

The source code

  • The React the source code. This is my former colleagues boast from the end of last year, said that I plan to be familiar with the React source code by June 2021, but at the beginning of reading too much source code, so I shelved. It took me almost two months to read the react-source-study code again. I have read it seven or eight times now
  • Redux, react – storyThe source code. Redux before is mainly to see a variety of source code analysis of the article, can be described as a hundred lines of source code, ten thousand lines of thought, and it used a lot of design patterns. It took me a week to read redux and React-Redux after reading the React source code. Redux itself is not difficult, but React-Redux may take a bit of time to digest. And the latest redux, etc. are rewritten in TS, this is praised, but also used React18use-sync-external-store, there is also the source code for this analysis. visibleRedux, React-Redux and related middleware source code analysis

  • Axios. Axios is a library that we use to request data all the time, so I was interested in the implementation of it. It took about three or four days to read it. It was relatively simple, but the joke is that AXIos is not written in TS. See axios source code analysis
  • React-router, react-router-dom, and history Is the latest version of V6, also with TS rewrite, previously wrote a column, interested can see. Meanwhile, I was also lucky to be a contributor for the React router, react Router – DOM and history source code analysis

Technology stack

This year, I have mainly mastered the following technology stack:

  • TS, you can now use it very skillfully
  • Mobx, the last company used DVA, so mobx was introduced this year. The former is declarative and the latter is responsive, similar to React and Vue
  • React-native, from zero to online project, also made a lot of mistakes. An article was summarized and output, but it was only sent to the company’s speaker because it was related to business

  • Taro small program, also from zero to online project, which involves Bluetooth printing also stepped on a lot of pits
  • Electron, mainly because the browser cannot automatically print, the automatic printing function after placing an order is realized through electron
  • Other such asWebpack5, Vite, and Babel. Webpack was read earlier this yeartapableAdvanced editionEventEmitter, webpack underlying foundation), recently looked atloader-runner, and some basic configurations;viteNow they are all used for personal projects, without any in-depth understanding. When can the company’s projects be smoothly switched tovite;babelOnly part of it, a little bitAST, learning is not comprehensive, these a few brush with it ~

Component library

The company’s component library is mainly maintained by me. However, when I took over, the component library was actually very difficult to use. For example:

  • In the previous Table component, adding selection, subTable, fixed column, and so on required the addition of various HOC
  • The Form has a single function. Each Form item has value and onChange
  • Many components will report an error if they don’t write props such as Value or data, or lack a generic prompt, and so on

In SASS, the background Table and Form Form occupy the majority, which undoubtedly brings great trouble to colleagues. In order to reduce the difficulty of development for colleagues, I have made many changes in the component library. I’ll use tables and forms as examples to describe how I modified the component library.

1. The Table

When I first came to the company, I asked my colleagues how to use HOC, and my colleagues were not quite clear about the order of HOC, so even my old colleagues might not be quite clear about how to configure HOC. Then to render a Table, I could only take the code of other colleagues before CV, but ACTUALLY I didn’t know why.

This is just arrived at the company to ask colleagues how to configure the Table HOC

I’m sure I can’t stand the above, and the other day IT occurred to me that where have I seen the various HOC nested in the following code?

const KeyboardVirtualTable = diyTableHoc(
    keyboardTableHoc(fixColumnsTableHoc(editTableHoc(TableVitualized)))
 )
 
 // How about the following?
 const KeyboardVirtualTable = applyMiddleware([
 diyTableHoc, 
 keyboardTableHoc, 
 fixColumnsTableHoc, 
 editTableHoc
 ])(TableVitualized)
Copy the code

Ah! The above code of various HOC is not similar to middleware!!

It’s impossible for me to remember HOC, never in my life, so one weekend, I put the above idea into practice:

// util.ts
// The onion model
constcompose = (... fns: HocMiddleware[]):HocMiddleware= > {
  fns = [...fns]
  if (fns.length === 0) {
    return (node: ReactNode) = > node
  }
  return fns.reduce((res, cur) = > (. args: any) = >res(cur(... args))) }/ / middleware
const applyMiddleware = (. middlewares: HocMiddleware[]) = > (node: ReactNode) = > {
  returncompose(... middlewares)(node) }export { applyMiddleware }
Copy the code

Redux implements compose and applyMiddleware, and then uses various isXXX prop to configure Table functionality:

function Table<D extends object = any> ({ isDiy, isBatchSelect, isExpand, isSort, isEdit, isSub, isKeyboard, isSelect, isIndex, ... res }: TableProps
       ) {
  const Table = useMemo(() = > {
    // Import on demand
    let keyboardTableXHOC
    if (isKeyboard) {
      keyboardTableXHOC = require('@gm-pc/keyboard').keyboardTableXHOC
    }
    // Configure the middleware
    const hocMiddles = [
      isExpand && expandTableXHOC,
      isBatchSelect && batchActionSelectTableXHOC,
      isSelect && selectTableXHOC,
      isIndex && indexTableXHOC,
      isDiy && diyTableXHOC,
      isSort && sortableTableXHOC,
      isEdit && editTableXHOC,
      isSub && subTableXHOC,
      isKeyboard && keyboardTableXHOC,
    ].filter(Boolean) as HocMiddleware[]

    constTempTable = applyMiddleware(... hocMiddles)(BaseTable)return TempTable as typeof BaseTable
  }, [
    isDiy,
    isBatchSelect,
    isExpand,
    isSort,
    isEdit,
    isSub,
    isKeyboard,
    isSelect,
    isIndex,
  ])

  const tableProps = (res as unknown) as TableProps<D>
  return <Table {. tableProps} / >
}
Copy the code

Well, now I don’t have to remember all kinds of HOC and its sequence any more. After I realized it, I couldn’t help feeling excited and shared the above results with the team members:

Of course, to the Table also added generic, Table header sort and other functions, specific can see GM-PC 1.2.3 major update TableX

2.ControlledForm<K>

Originally, form components had to pass corresponding value and onChange, which could not realize functions such as unified management and form item linkage, resulting in redundant code and unfriendly to front-end developers. Therefore, it is urgent to control forms to solve this problem.

Note that the controlled forms mentioned above actually mean that the Form handles value and onChange automatically, rather than the developer writing it by hand. Since the original Form is already occupied, I’ve given it a new component name. The antD function is referenced by using a Context in the Form and then:

  • Through theControlledFormIn theControlledFormContextcontextProvideCorresponding form values and methods for modifying form values (providerValues), and thenControlledFormItemThrough theuseContextGets the value of the context
  • ControlledFormItemThe components in theThere is no need to pass value and onChange, source code basedvaluePropName? : 'value' | 'checked' | 'selected' | 'date'.trigger? : string(component changes the value of the callback function name, such as onChange) hijacking the component, add the corresponding value and trigger functions to the component, throughReact.cloneElementClone a new component
function ControlledFormItem<T = any> (props: ControlFormItemProps<T>) {
  const {
    name = ' '. restProps } = propsconst{... } = useContext(ControlledFormContext)constchildProps = { ... children.props, }// If name is provided
  if (name) {
    // Intercept plus valuechildProps[valuePropName] = values? .[name]const triggers = new Set<string>([trigger])
    if (!Array.isArray(children)) {
      triggers.forEach((eventName) = > {
        childProps[eventName] = (args: any) = > {
          // Trigger the update
          if (onChange) {
            const newValue = onChange(name, args)
            if (onFieldChange && resetFields && getFieldsValue && setFieldsValue) {
              onFieldChange(newValue, { resetFields, getFieldsValue, setFieldsValue })
            }
          }
        }
      })
    }
  }
  ...

  return (
    <FormItem {. restProps} >
      {cloneElement(children, childProps)}
    </FormItem>)}Copy the code

No more manual controlled components, no more redundant vlaue and onChange writing

Of course, the lists and forms mentioned above will certainly include various generic implementations:

Gm-pc 1.2.3 Major update, GM-PC 1.3.3 form validation

Non-technical

1. Finished reading Volumes 1 to 8 of MAO Selected

I learned to look at problems from the perspective of development; No investigation, no right to speak; Theory of practice and contradiction; Revolutionary optimism; Know the world, change the world and so on. It is indeed a treasure trove of books, but I only read them from cover to cover the first time, intending to read them more for decades to come.

Finished reading the Dream of Red Mansions

Then I spent some time to collect some information about the dream of red Mansions, such as background, interpretation, evaluation of each person and so on.

3. Reviewed some of Lu Xun’s novels

Such as “The Scream”, “Diary of a Madman”, “Kong Yiji”, “Medicine”, “Storm”, “Hometown”, “Ah Q” and so on.

4. Revisit Norwegian forest novels and movies

“Norwegian Wood” is a novel I like very much. I saw it in my sophomore year. I re-enjoyed it this year.

5. Finished reading 100 episodes of Chinese history

From March to December, I watch a little bit every morning. After reading it, I feel that the rise and fall of each dynasty in ancient times are so similar, and the probability of success is relatively high if the historical figures can live long enough.

6. The Long March, the Three Battles of the War of Liberation, and the Korean War

Find some historical information, background and characters mentioned above on B station and Zhihu. A former colleague of mine said “you are the only one of my friends who studies these wars” lol. Of course, I only know a little about the surface, just more interested in these.

As an interviewer

As an interviewer, I have always been the interviewer before, and I have also experienced some interviewer’s commanding. Therefore, I was thinking that if I become an interviewer in the future, no matter how the interviewer is, I should respect each other. After all, people come all the way to interview, not to be wronged.

If I don’t or don’t get it right during the interview, I’ll point out why I did it wrong (if I have time) and make the interview more productive. At the end of the interview, I would say thank you for your time. After all, wasting someone’s time is like killing them. Everyone’s time is very valuable. In this way, the other party will have a good impression of our company. After all, how the interviewer’s attitude determines the first impression of the company.

Here are some of the candidates’ comments, which were nice to see:

The outlook for 2022

  • Continue to deepen engineering, do tool chain, in-depth study of Babel, AST, vite and so on
  • React is almost done. I hope to study Vue next year. At present, I only know how to use it
  • React, Vuecontributor
  • Learning technology needs to be combined with business and service business, hoping to have a deeper understanding of the company’s business, so that development can be relatively easy
  • Explore three.js, the Node framework Nest or Egg or Midway?

The last

2021 met a lot of big guys, many of them younger than me, they are so young, fierce and hard working, compared to them, I am really a chicken. But I believe that as long as progress a little bit every day, eventually it is just a matter of time, I hope to be like them one day ~

Thank you for reading this. Finally, I would like to conclude this article with the last paragraph of “On Practice” :

Truth is discovered through practice, and truth is proved and developed through practice. From perceptual knowledge and active development to rational knowledge, and from rational knowledge and active guidance of revolutionary practice, transformation of the subjective world and the objective world. Practice, knowledge, practice, and knowledge are repeated endlessly, and the contents of each cycle of practice and knowledge are comparatively advanced to a higher degree. This is the whole epistemology of dialectical materialism, its unity of knowledge and action.

2022, keep working hard, come on! You!!!!!