Application State Management Tool Redux VS Mobx for Wechat applet

Keywords: JSON Programming React Vue

First, how to define the application state of the Wechat applet itself?

page({
  data: {
    item: '',
    isLoading: true
  },
  onLoad: function(){
    this.setData({
      isLoading: false
    })
  }
})

2. Why use application state management tools?

  1. Same data, one request, application global sharing.
  2. The clear data flow in MVVM architecture development is one-way data flow.
  3. The data and application state scattered on different pages are unified managed, and data and state changes are shared.
  4. It can adapt to the data structure of component and modular development, improve code reuse rate and development efficiency.

3. What are the application state management tools?

There are many front-end MVVM infrastructure libraries. At present, the mainstream ones are React, Vue and Angular. Different libraries have different application state management schemes, such as Flux, Redux, Mobx, Vue's Vuex, Angular's ngrx/store. Redux is not the exclusive of React, but the best solution for Redux. Of course, Redux can also be transplanted to other frameworks, such as can be used. It is used in Wechat applet.

Fourth, how to choose the application state management tool library for the Wechat applet?

At present, Wechat has transplanted Redux and Mobx as application state management. Both Redux and Mobx are hot data flow models. A back-to-back function seems to be an open source boundary matching, an object-oriented, low-key forward.

Functional vs Object-Oriented

The advantages of functional formulas are:

  • Separating data and processing logic, the code is more concise, modular and readable.
  • Easy to test, easy to maintain, easy to simulate the test environment
  • High reusability of logical code

Relatively Object-Oriented Programming:

  • The weak type of javascript indicates that it is object-based and not suitable for full functional expression.
  • Mathematical thinking and data processing are suitable for function, while business logic processing is suitable for object-oriented.
  • Functional programming with rigorous logic is quite perfect, but in order to achieve specific business functions, more fine-grained code has to be written to achieve, while the object-oriented approach is more concise and flexible.

Redux vs Mobx

As for these two models, there are some specific advantages and disadvantages.

Let's start with the features of Redux:

### reducer

import { combineReducers } from 'redux'
import { createReducer } from 'redux-immutablejs'
import { fromJS } from 'immutable'
import {
  EXAMPLE
} from '../constants'

const example = createReducer(fromJS({
  title: "Successful project construction"
}),{
  [EXAMPLE]: (state, action) => {
    return state.merge({
          title: action.payload.title
    })
  }
})

const rootReducer = combineReducers({
  example
})

export default rootReducer

### action

import {
  EXAMPLE
} from '../constants'

function example(val){
  return {
    type: EXAMPLE,
    payload: {
      title: val
    }
  }
}

export function changeTitle(val){
  return (dispatch, getState) => {
    dispatch(example(val))
  }
}
  • Declarative programming reducer
  • Pure function action has no side effects
  • immutable data

Compare Mobx:

var extendObservable = require('../libs/mobx').extendObservable;
var apiPath = require('../config/apiPath')
var {formatTime} = require('../utils/tool')

var app = getApp()

var userInfo = function(){
  extendObservable(this,{
    title: 'My appointment',
    data: {},
    order: []
  })
  this.receive = function(){
    var that = this
    app.getUserInfo(function (userInfo) {
      that.data = userInfo
    })
  }
  this.getUserOrder = function(){
    var that = this
    wx.request({
      url: apiPath.GETUSERORDER,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token') || []}`,
        'Content-Type': 'application/json'
      },
      success:function(json){
        if(json.statusCode == 200){
          that.order = json.data
        }
      },
      fail:function(e){
        console.log(e)
      }
    })
  }
}
  • Data flow is not natural, only the data used will cause binding, local accurate updates, but it avoids the worry of granularity control.
  • To be able to retrieve time, you need to build your own retrospective data, which is more complex because there is only one reference to the data.
  • There is no need for immutable and no additional overhead for copying objects.
  • Data flow is composed of function calls, which is easy to debug.
  • Because there is no magic, there is no middleware mechanism to speed up work efficiency through magic (here magic refers to the process of action distribution to reducer).
  • Perfect support for typescript.

How to Choose in Project

The more essential difference between the two is that Redux separates state and action, so an action can distribute data to multiple states, which belong to the global unique store; and action in Mobx belongs to the global unique store.
The object object object defined by the store can only process its own state. The more complex the project, the more obvious the advantages of Redux.

From the current experience, it is recommended that the front-end data flow is not too complex, using Mobx, because it is clearer, less code to achieve the same business; if the front-end data flow is extremely complex, it is recommended to use Redux+immutable to alleviate the huge business complexity through middleware. In addition, typescript can be used to assist with Mobx.

5. Using Mobx in Small Programs

Because of the characteristics of the widget framework itself, componentization is more complex in widget projects, so the page will not be divided into fine-grained components, so using Mobx is more flexible for widgets.

index.js

var observer = require('../../libs/observer').observer;
var Toast = require('../../components/toast/index')

Page(observer(Object.assign({}, Toast, {
  props: {
    userInfo: require('../../stores/userInfo').default
  },
  onLoad: function () {
    this.props.userInfo.receive()
    wx.setNavigationBarTitle({
      title: 'My'
    })
  },
  onShow: function (){
    this.props.userInfo.getUserOrder()
  }
})))

index.wxml

<import src="../../components/toast/index.wxml" />
<template is="zan-toast" data="{{ zanToast }}"></template>
<view class="container">
  <view class="userinfo">
    <image class="userinfo-avatar" src="{{props.userInfo.data.avatarUrl}}" background-size="cover"></image>
    <text class="userinfo-nickname">{{props.userInfo.data.nickName}}</text>
  </view>
  <view class="userorder">
    <view class="userorder-title">{{props.userInfo.title}}</view>
    <view class="userorder-list">
      <view class="orderinfo" wx:key="{{index}}" wx:for-index="key" wx:for="{{props.userInfo.order}}">
        <view class="orderinfo-date">Departure time:{{item.trainDate}}</view>
        <view class="orderinfo-traininfo">Traffic information:{{item.trainCode+' '+item.startCity+'-'+item.endCity+' '+item.seatName}}</view>
        <view class="orderinfo-date">Time of appointment:{{item.created}}</view>
      </view>
    </view>
  </view>
</view>

VI. Reference Documents

Mobx document http://cn.mobx.js.org/

Widget document https://mp.weixin.qq.com/debug/wxadoc/dev/index.html

Small Procedure Case: Railway Ticket Query | Balance Ticket Reservation Notice https://github.com/Vizn/wechat_ticket


Scanning Experience Program
PS: Next article will analyze the internal operation mechanism of Mobx in detail. Please look forward to it.

Posted by common ground on Sun, 26 May 2019 13:11:41 -0700