Install dependencies

npm install mobx --save
npm install mobx-react --saveCopy the code

Store the container

Counter module

import { observable, action, computed, autorun } from 'mobx'
export default class Synchronous {    
    @observable  initState = "Counter"@observable count = 10 /* Counter increase */ @Action Incement = Val => this.count += Val /* Counter decrease */ @Action Decrement = Val => this.count -= val }Copy the code

The index is derived

import Synchronous from './Synchronous'
export default {    
    Synchronous:new Synchronous()
}Copy the code

Top-level components

import { Provider } from 'mobx-react';
import store from './Store'<Provider {... store}> <App/> </Provider>Copy the code

Page component usage

index

import React from 'react'
import ConponentOne from './ConponentOne'
import ConponentTwo from './ConponentTwo'
export default function index() {    
    return(<div> <ConponentOne/> <ConponentTwo/> {/* State of shared component one */} </div>)}Copy the code

ConponentOne

import React from 'react'
import { observer, inject } from "mobx-react";
import { Button } from 'antd'

@inject("Synchronous")
@observer
class ConponentOne extends React.Component {    
    constructor(props){        
        super(props)        
        this.state = {}    
    }    
    render(){const {initState,count} = this.props.Synchronous /* const {Incement, Decrement} = this.props.Synchronous /* Deconstruct the shared method */return(< div > < h1 > component a - {initState} {/ * initialized state * /} {count} {/ * initialize counter * /} < / h1 > < Buttontype="primary"OnClick ={() => Incement(2)}> add </Button> <Buttontype="primary"The onClick = {() = > decrement (1)} > reduce < / Button > < / div >)}}exportDefault ConponentOne /* Export */Copy the code

ConponentTwo 

import React, { Component } from 'react'
import { observer, inject } from "mobx-react";
@inject("Synchronous")
@observerclass ConponentTwo extends Component {    
    render() {const {count} = this.propsreturn(< > < h1 > component 2 - Shared state - counter {count} < / h1 > < / a >)}}export default ConponentTwoCopy the code

The principle of

  1. The @Observable module defines the shared state, and the @Action module defines how to change the state
  2. Mobx-react provides a Provider to wrap the App, passing the Store inject to the props of the component
  3. Observable decorates the component, refreshing the component to share when state changes