preface

Mobx, like Redux, has a one-way flow of data. It uses action to change state and force view updates. The main purpose is to simplify the process of data sharing between components & ensure a unique data source.

Using the process

  1. Define the state to make it observableobservable
`@observable name = 'zoe'; ` `@observable age = '27'; `Copy the code
  1. createaction, some actions that change state values
  @action  addAge = () => {
    this.age += 1;
  };
Copy the code
  1. Create views that respond to state changes@observer
class Store { @observable name = 'zoe' @observable age = '27'; @action addAge = () => { this.age += 1; }; } @observer class Counter extends ReactDOM.Component { store = new Store(); render() { return ( <div> {this.store.age} <button onClick={() => { this.store.addAge(); }} > + </button> </div> ); }}Copy the code

observable

  • View data printouts wrapped as an Observable

ObservableObjectAdministration

let o=observable({name:'name is zoe'}) console.log({o}) // Proxy {Symbol(mobx administration): ObservableObjectAdministration} o.n ame = 'hello zoe' console. The log (o.n ame) / / name is zoe, besides the action are not to change the stateCopy the code
  • Observables turn normal data into observable data that is not the original data type (e.g., an array from a store)toJS(someArray)Scroll down, otherwise you can’t use the method on the Array prototype directly.)

Copycat Observable

Train of thought

  1. The Proxy Proxy wraps the data into observable Proxy data
  2. The first issue to consider during prox proxy packaging is this deeply nested object (using recursive deepProxy)

implementation

An aside: ES7 decorator is dependent on Object.defineProperty

  • The decorator retrieves target data, intercepts it, calls the wrapper function, wraps it, and returns the corresponding MOBx data of the same name
function observable(target, key, Descriptor) {// Use descriptor. Initializer to get the value of the object we decorate and wrap it if (typeof key === "string") {let v = descriptor.initializer(); v = createObservableAnnotation(v); return { configurable: false, enumerable: true, get() { return v; }, set(value) { v = value; // Set when Autorun executes, automatically updates the component},}; } return createObservableAnnotation(target); }Copy the code
  • createObservableAnnotation
Function createObservableAnnotation (val) {let handler () = = > {/ / connection for autorun, don't do here into}; return deepProxy(val, handler); }Copy the code
  • DeepProxy recursively wraps deeply nested objects
Function deepProxy(val,handler) {// If (typeof val! == "object") return val; Val [key] = deepProxy(val[key], handler); Return new Proxy(val,handler()); return new Proxy(val,handler()); }Copy the code

summary

Today no summary, a happy Mid-Autumn Festival