The main purpose of this article. React and MOBx demo. Learn how mobx works in react. I will write this article in plain English; React and React-Native integrate mobx project demos at the end of the article. The react-Native implementation is the same as the following.

#####1. Create-react-app create a react project scaffolding command to generate a react project:

NPM install mobx mobx-react --save 3. NPM install mobx mobx-react react-router --saveCopy the code

Install the above dependencies. Let’s modify the project structure —- you can modify it yourself;

#####2. Implement react-router mobx is known for its ability to share data across pages. That we first realize the jump page function; Let’s start by modifying the following files — 1.home.jsx

import React, { Component } from "react";
 class Home extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }
  render() {
    return<button onClick={() => {this.props.history.push()"/one"); </button> </div>); }}export default Home
Copy the code

2.one.jsx

import React, { Component } from "react";
class One extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }
  render() {
    return<div> <h1> < buttonclick ={() => {this.props.history.push()"/"); </button> </div> }}export default One
Copy the code

3.router.jsx

import React, { Component, Fragment } from "react";
import { HashRouter,Route } from "react-router-dom";
import Home from '.. /page/home';
import One from '.. /page/one';
class Router extends Component {
  render() {
    return( <HashRouter> <Fragment> <Route exact path={`/`} component={Home} /> <Route path={`/one`} component={One} /> </Fragment> </HashRouter> ); }}export default Router;
Copy the code

4. Entry of the index.js file

import React from 'react';
import ReactDOM from 'react-dom';
import Router from './router/router';
ReactDOM.render(<Router />, document.getElementById('root'));
Copy the code

NPM start = NPM start = NPM start = NPM start = NPM start

Important note –MobX uses the ES7 decorator syntax, which is currently experimental, and projects created using the create-React-app scaffolding do not have decorator syntax enabled by default. Need some extra configuration check out this article :create-react-app config modifier this may be a bit of a hassle —– my current solution is this – I will update it as soon as possible

#####3. Use of mobx and Mobx-React 3.1 requires the addition of a store folder under the project structure SRC – the purpose of this folder. We understand it as a place for storing and managing data sources;

Create 3 js files – homestore.js, onestore.js, index.js – add code to each folder homestore.js: class that holds a page data source

import { observable} from "mobx";
class HomeStore {
  @observable homeNum = 0;
}
export default HomeStore;
Copy the code

Onestore.js: class that holds a page data source

import { observable} from "mobx";
class OneStore {
  @observable oneNum = 3333;
}
export default OneStore;
Copy the code

Index. js: To merge multiple stores into one object

import HomeStore from "./homeStore";
import OneStore from "./oneStore";
let oneStore = new OneStore();
lethomeStore = new HomeStore(); const stores = { oneStore, homeStore }; /// Default export interfaceexport default stores;
Copy the code

So what’s the point of creating these folders. In fact, an xxxStore is a place for data sources. Each class can define the data we need to use – just like the state in React; What index.js does is put all the data in one place — it’s actually a setup for the next one;

3.2 Project entry Index. js part of the code to modify index.js

import React from "react";
import ReactDOM from "react-dom";
import Router from "./router/router";
import { Provider } from "mobx-react";
import stores from "./store"; ReactDOM.render( <Provider {... stores}> <Router /> </Provider>, document.getElementById("root"));Copy the code

Here we introduce the Provider and store mentioned above. This side is actually a data container, which is also the basis of data sharing implemented by data flow frameworks like MOBx. Our child components are placed in this data container. Mobx can achieve cross-component data sharing Provider is actually no stranger. React Context is a property of the React context.

3.3 Page /home. JSX code changes since Provider is a data container. Our child components are inside the container. How does our child component use the data in the container

import React, { Component } from "react";
+ import { observer, inject } from "mobx-react";
+ @inject("homeStore")
+ @observer
class Home extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }
  render() {
    return(< div > + < h1 > home page number of the data source is: {this. Props. HomeStore. HomeNum} < / h1 > < button onClick = {() = > {this. Props. History. Push ("/one"</button> </div>); }}export default Home;
Copy the code

The + in the code is the newly added code. Observer: Make your component a responsive component. Is the data changes can be started to re-render. Inject (homeStore): Registers data to components like Redux’s Connect. HomeStore is actually the name of our new instance in store/index; This. Props. HomeStore. XXX: this is how to use the values in the data source. Just like component passthrough

3.4 How do I Modify the Data Source? Now that we’ve implemented the presentation of the data, of course we need to manipulate the data – let’s go to the next operation @action: request meaning – in strict mode. This is the only operation that operates on store; + represents new code

  • Modify the store/homeStore. JsModifying a data source
//homeStore.js
import { observable,action} from "mobx";
class HomeStore {
  @observable homeNum = 0;
  + @action addNum() {
  +  this.homeNum += 1;
  + }
  + @action lessNum() { + this.homeNum -= 1; +}}export default HomeStore;
Copy the code
  • Modify the page/home. JSXShows the add action buttonWe’ll use it for @action defined in storethis.props.home.addNum()Operation will do
  render() {
    return// Add the code itself... + + < div > < h1 > home page number of the data source is: {this. Props. HomeStore. HomeNum} < / h1 > + < button onClick = {() = > {this. Props. HomeStore. AddNum ()}} > + click on add + < / button > + < button onClick = {() = > {this. Props. HomeStore. LessNum ()}} > + click delete + </button> + </div> ; }}export default Home;
Copy the code

3.5 How to Use Shared Data? Now that the display and modification operations are complete — the next step should be mobx sharing data. How to implement data sharing. It’s easy to just look at the code – add @inject(“homeStore”) to the data source page we need to use – and of course modify shared data

import React, { Component } from "react";
import { observer, inject } from "mobx-react";
@inject("homeStore")
@inject("oneStore")
@observer
class One extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }
  render() {
    returnA (< div > < h1 > page < / h1 > < h1 > home page number of the data source is: {this. Props. HomeStore. HomeNum} < / h1 > < h1 > oneStore number is: {this. Props. OneStore. OneNum} < / h1 > < button onClick = {() = > {this. Props. History. Push ("/"); </button> </div> }}export default One
Copy the code

Go to the second page to see the data display:

That’s the end of the process

#####4. Strict mode Settings if we don’t apply strict mode. You can have such a SAO operation; Use drop code in a page:

this.props.homeStore.homeNum = 33;
Copy the code

You will find that your data source has been modified. But this is a dangerous operation and the data source becomes untraceable

+ import { configure } from "mobx"; // add render(<div> <Provider {... stores}> <XXX /> </Provider> </div>, document.getElementById("root")); X version strict mode enforceActions + configure({+ enforceActions:"observed"+});Copy the code

This will enable strict mode – the advantage is that the only action to manipulate the data source is through action. Data flow can be traced ~ TOdo: the code still needs to be optimized in many places 1.@observer cannot be placed before export default 2. The support for the create-react-react decorator is a little bit of a hassle so that’s the end of the article everywhere; It’s easier to write. Webpack-mobx, create-react-app, webpack-mobx, create-react-app, webpack-mobx, create-react-app React-native integration mobX project

Write their own boring small program welcome bug