mobx状态管理使用

995 阅读1分钟

安装依赖

npm install mobx --save
npm install mobx-react --save

store容器

计数器模块

import { observable, action, computed, autorun } from 'mobx'
export default class Synchronous {    
    @observable  initState = "计数器"    
    @observable  count = 10     

    /* 计数器增加 */    
    @action Incement = val => this.count += val        

   /* 计数器减少 */    
    @action decrement = val => this.count -= val    
}

index导出

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

顶级组件

import { Provider } from 'mobx-react';
import store from './Store'

<Provider {...store}>       
    <App/>
</Provider>

页面组件使用

index

import React from 'react'
import ConponentOne from './ConponentOne'
import ConponentTwo from './ConponentTwo'
export default function index() {    
    return (        
        <div>            
            <ConponentOne/>             
            <ConponentTwo/>  {/* 共享组件一的状态 */}        
        </div>    
    )
}

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  /* 解构出共享方法 */       
         return (            
                <div>                
                    <h1>   
                        组件一 - {initState} {/* 初始化状态 */}                   
                        {count}  {/* 初始化计数器 */}               
                    </h1>                
                    <Button type="primary" onClick={ () => Incement(2) }> 增加</Button>   
                    <Button type="primary" onClick={ () => decrement(1) }> 减少</Button> 
                </div>       
         )    
    }   
}

export default ConponentOne  /* 导出 */

ConponentTwo 

import React, { Component } from 'react'
import { observer, inject } from "mobx-react";
@inject("Synchronous")
@observerclass ConponentTwo extends Component {    
    render() {
        const { count } = this.props.Synchronous  /* 解构状态 */        
        return ( 
               <> 
                   <h1> 组件二 - 共享状态 - 计数器 { count }  </h1>          
               </>       
        )   
    }
}

export default ConponentTwo

原理

  1.  模块内 @observable定义共享状态, @action定义修改状态的方法
  2.  mobx-react 提供了 Provider 来包裹App,传递 store                                             inject 用来将对应 store 注入到组件的props
  3.  @observable 修饰组件,当状态变化,刷新组件达到共享