Ten minutes to get started with the best practices of front-end React+MirrorX

With the popularity of React, the front-end of many big companies must have React-related knowledge, and even mature frameworks have been applied in the production environment. Today we are discussing the MirrorX writing problems often encountered by React advanced users. Looking at the components written by the predecessors, we are confused when we go around. Real case: In order to change a simple parameter, the front-end development engineer will spend at least 4-5 hours following the code. So I made this article to help front-end engineers who are in the advanced process quickly understand how a RESTful request is processed by MirrorX to reach the component and stimulate the component to re-render. This article is a must for front-end development.

Suitable for readers: programmers with React foundation, UCF developers, Antd developers.

1. Concept question and answer

1. What is MirrorX?

MirrorX is a state machine based on Redux package. For example, in actual use, suppose we want to read a product interface from the background, process the data returned by the interface (for example, if the discount is discounted, the front-end calculates the discount amount), and then display the processed data on the interface. Think about it, you have to use a lot of code, and it must be placed in the component class?
If there is a framework, only one line of code in the component can be solved. Isn't it great? MirrorX is used to do this.

2. How can it be solved in one line?

Those who have studied object-oriented programming should know that encapsulation can make the control layer code more concise. But if you want to deal with the thing just mentioned in React, you need not only state and props control, but also the context of coming and going (such as who the current user is, what the VIP level is), what makes React programmers most uncomfortable , The current user information is in the UserView component, and the current GoodsView component does not have access to the UserView component. Therefore, there needs to be a unified place to overcome the barriers of components, store this information, and encapsulate this mechanism to achieve a one-line solution.

3. What is the specific mechanism?

There are many articles on the Internet about Redux. After reading Redux, you can search for MirroX to know the specific mechanism. To put it simply, the system has several state warehouses . We can put context variables in different warehouses, such as user information and product information; when they are placed, they are all implemented by calling actions , such as reading product information, Change the quantity of the product. The action can choose whether to call the service . If the front desk changes the number of products, you can directly change the value in the status warehouse without calling the service; if the service is called, the function generally requires server interaction.

2. How to use MirrorX to complete a function

Here is an example of requesting the background to read the product list

1. Environmental preparation

First make sure you have installed mirrorx, react, axios via npm i. Because this article is a best practice, I won’t go into details on how to install it.

2. Write a simple service (Service)

Write a service.js file (there are many comments, the code is actually not a few lines)

import request from "axios";
const URL={
    
    
    GET_GOODS:"api/template/GetGoods" // 声明要访问的后台接口地址
}
// 暴露出一个名为GetGoodsApi的函数,入参params是Object类型,代表提交给后台的参数列表
// 这个函数会返回一个Promise对象
export const GetGoodsApi = (params) => {
    
    
    return request(URL.GET_GOODS, {
    
    method: "post",params})
}
// 你还可以暴露出其他函数,一个Service可以export const多个函数
// export const GetMember = (params) => {
    
    
//    return request(URL.GET_MEMBER, {method: "post",params})
//}

3. Write a simple model layer (Model, including actions and models)

Write a model.js (a lot of comments, the code is actually not a few lines)

import {
    
     actions } from "mirrorx";
import * as api from "./service"; // 把刚才的service.js引入进来,名称定为api

export default {
    
    
    name: "GoodsManager", // 这里写的名字将会成为状态仓库的名称
    initialState: {
    
     // 这里可以写初始化时状态机里的初始状态
    	userId: "0001"
	},
    // reducer:状态机处理函数
    reducers: {
    
    
    	// 这个updateState是默认的,它用来主动更新状态机里的各种状态
    	// state和data都是Object对象
    	// state是框架传入的,开发者调用的时候,data才是对应的第一个参数
    	// ...是ES6的对象扩展运算符,后面...data会自动覆盖...state的同名属性
        updateState: (state, data) => ({
    
     ...state, ...data })
        // 后面还可以写其他的reducer,切记第一个参数一定是state
    },
    effects: {
    
    
    	// 动作处理函数:获取商品
    	// param是对象,getState是框架传入的函数对象,用来方便获取当前状态机的状态
    	// 开发者调用的时候,不用给getState形参赋值
        async GetGoods(param, getState) {
    
    
        	// Promise的同步操作运算,获取Axios返回的data
            let {
    
     data } = await api.GetGoodsApi(param);
            // 调用当前状态机的updateState方法(也就是上面写的那个函数)
            // 由调用可见,只放了一个Object类型的参数
            actions.GoodsManager.updateState({
    
     goods: data.data });
        }
    }
};

4. Transform the components to be hosted by MirrorX

The first step is to add in the entry of the project (for example, add the code to create a state machine in memory on app.js):

// 引入MirrorX的组件
import mirror from 'mirrorx';
// 引入刚刚写的model,注意路径
import model from './model';
// 调用MirrorX,根据模型创建状态机
mirror.model(model);

Step 2: Change the code on the components managed by the state machine

// 增加对MirrorX的引用
import {
    
    connect} from 'mirrorx';
// 这里面GoodsView就是当前受状态机托管组件的class名称,GoodsManager就是第二步里name写的名字
export default connect(state => state.GoodsManager)(GoodsView);

5. Write the following code where you need to call:

Here, because GoodsView needs to display the list of products as soon as it is loaded, we can write the code in the constructor(props) function:

// 组件上需要引入MirrorX的actions
import {
    
    actions} from 'mirrorx';
// 在constructor(props)函数里写上以下调用即可
actions.GoodsManager.GetGoods({
    
    
	user:props.userId
});

Then write the front-end code of the rendering interface from props.goods (called goods because the third step GetGoods method calls the updateState method when the updateState method is called, so the current component needs to be connected from props) in the render interface, and you can start testing.

Three, supplementary explanation

  1. All state values ​​in the state machine will be automatically written in the props of the managed component. When changes occur, they can also be taken out of the props, so don't try to get or update the component's state.
  2. As long as the value in the state machine changes, the managed component will re-execute the render method to achieve automatic refresh.
  3. In actual development, due to component nesting, component element attribute values ​​conflict with state names in the state machine, various intractable diseases will follow. Based on my analysis and actual combat of mature frameworks such as Antd and UCF, I came to a conclusion that there are generally no more than 5 model.js and service.js for large systems, and most of them have naming conventions.
  4. If you are looking at other people's code, just look it up in order, and the code of the front-end god is no longer difficult to understand.

Guess you like

Origin blog.csdn.net/yry0304/article/details/104853557