purpose

Let’s get straight to the point: this article is a new status management library for amway. If you use React, you’re more familiar with object orientation, admire vue’s simplicity, and feel a little irritated by Redux. Try mobx.

Amway, with a little content. Content start

content

After seeing the author of Redux, I recommended the Mobx library on Twitter:

unhappy with redux? try mobx

The great God offers to replace his famous work? !!!!!!!!!

I tried it right away. In less than one afternoon, I basically got used to it. Then IN the evening, I went back to think about code organization and tried it out. I found that the development efficiency was greatly improved, and the whole project was clear.

And then when I think back to redux, I really feel like I’m not smart enough. After reading the documents for a week, I had no idea how to write code. Then because the source code is not much, and looked at redux source code for a week, but also found a bug, raised PR, but still do not know how to write code. Finally, I had to copy other people’s code without thinking and understood the whole process roughly.

Therefore, from the comparison of their actual situation, once a little silly X became Redux brainless black, and said on many occasions, who uses Redux who works overtime… Now think too Simple

After a lot of discussion, the biggest reason redux is uncomfortable is not familiar with functions, and JS itself does not provide much syntactic convenience for functions.

Redux is more of a specification, and then provides several helper functions in order to apply the specification to the project. If you are familiar with the function, you will identify with it and feel comfortable using it.

However, the number of engineers who are familiar with functional expressions is much smaller than the number who are familiar with object orientation, and I have only scratched the surface of functional expressions.

Anyway, let’s take a look at Mobx.

Write react using Mobx. In general, there are two steps:

import $ from 'jquery' // just for ajax usage import { observable } from 'mobx' class Posts{ @observable list=[] // For demonstration purposes, just $.ajax. // But this model is very difficult to test!! fetchPosts(){ $.ajax({ url:'/posts' }).done((data)=>{ this.list = data.postList }) } }Copy the code

This for people familiar with OOP, friendly not, write model class this matter, some experienced engineers, not write thousands, also write hundreds of it. Asynchronous processing, which is pretty straightforward, requests, and then processes the corresponding properties based on the requested data. This code, without the introduction of ES6 syntax, is no different from the old days of jquery writing model.

There’s an @ Observable here. The decorator is currently not finalized in ES7, but is also required to be used with Babel 6 by introducing a plugin that can be used here to improve readability. You can do this without using a decorator. In principle, you wrap a function in the list that handles the list and makes reading and writing on the list pub/sub.

Of course mobx offers a lot more than that, according to the official description

MobX is a battle tested library that makes state management simple and scalable by transparently applying functional reactive programming (TFRP)

Battle tested, Transparently applying functional Programming

Mobx does a great job of letting you just focus on manipulating object properties, and the idea behind that is one sentence

Anything that can be derived from the application state, should be derived. Automatically.

The state of the application is the source, and everything else should be derived from the source. The Posts class above, for example, comes from @Observable List. Then the rest of the section relies on this list to do things, such as mobx’s autorun function

Autorun (()=>console.log(this.list.length))Copy the code

The anonymous function in Autorun evaluates the list. Mobx knows that the side effect function depends on the list, so if the list changes, it executes this function. This function is run by the list application state. If the application has other states, Mobx will not fire this function because it only relies on list.

React changes to the UI are a side effect of state changes. So it’s natural

autorun(()=> redner(this.list))
Copy the code

This is why mobx does not need special performance optimizations. UI is only affected by state changes, and UI changes only when this. List changes. In fact, official Mox-React does a lot more work on rendering only the components that render requires.

2. Write the React component

With class Posts above, we have a component to display the Post list

import React from 'react' import { observer } from 'mobx-react' import Posts from './Posts' @observer class PostListComp  extends React.component { contructor() { this.posts = new Posts(); this.posts.fetchPosts() } render() { return (
       
    {this.posts.list.map((post)=>(
  • post.title
  • ))}
)}}Copy the code

Here the Posts instance is not intended to be used globally, so it is assigned to this. Posts. This.posts. List is null in ul, fetchPosts is asynchronous, and this.posts. List has data from the server. Then render it. That’s it.

The state here is handled by the PostListComp component itself and is not shared with other components; If you want to share it, you can instantiate it from the common ancestor of both components and pass it in separately, or even make it a global singleton depending on the business. Think of all the tricks you can use with objects, and if you want to use DI to manage those objects, you can, too. There are articles about mobx in conjunction with InversifyJS.

Posts. list changes will only re-render PostListComp, not the parent component, if the parent component doesn’t need posts.list for rendering. Only Render needs Render’s components, so performance is superior. You can even do something like this (don’t sweat the details of the code below)

const profileView = observer(props => {
       if (props.person.nickName)
          return 
       
{props.person.nickName}
else return
{props.person.fullName}
}); Copy the code

If the nickName is not empty, then Mobx knows that the view only relies on the nickName, and that the fullName change does not cause the view to change and thus does not cause the new Render component to change. Only Render needs render’s components (I’ve already said that 3 times!).

The other API

Mobx also provides other apis that are relatively advanced, such as

  1. @ Computed: Indicates the state generated by the original state. For example, fullName is generated by firstName and lastName. If firstName changes, fullName is recomputed. Listening for the @computed attribute is the same as listening for the @Observable attribute. In theory, you can write an infinite number of layers of such dependencies.

  2. Untrack: Used a property of state at some point, but did not want to rely on it

  3. Transaction: Attribute modifications performed in a transaction block trigger a Derivations change or execution only at the end of the block. This avoids unnecessary multiple side effects, such as multiple Render React components.

  4. UseStrict: For mobx in non-strict mode, state can be changed anywhere, which quickly makes the management of state difficult to maintain. In strict mode, only functions marked @Action or code in the runInAction can modify state. This is highly recommended

  5. Spy & Intercept does individual or global state interception. So that’s a nice convenience for things like log.

There’s a few more. Go read the documentation.

digression

The model changes, the UI automatically changes, mobx writes, makes me feel vUE. It just feels like a few more decorators.

disadvantages

The community is not rich enough. Mobx materials are not much, basically no Chinese materials. My amway classmates all reported that the official Get Start (English) looked a bit painful. And I said, think about the first demo you wrote about Redux, and they said that the pain was nothing.

I’m sure you already have some projects using Redux, but if it’s working, there’s no need to switch. I also maintain projects that use Redux and then use Mobx for new projects, and my productivity has improved dramatically, but the cost of rewriting old projects is too high…

conclusion

So, if you use React and are more familiar with object orientation, and admire vue for its simplicity and intuition, try mobx. Write very comfortable, and the performance of the program is guaranteed. By the way, dev-tools is also available, which is nice enough to see which components have been rerendered.

If you are successful amway, want to look at mobx, advice from the official beginning of the document, or go to the official recommendation list, look for video tutorials (don’t want to, must be in English), the address is mobxjs. Making. IO/mobx/FAQ/bl…

A starter is also available, which eliminates various configurations.