• Mobx学习之路----强大的“状态管理工具”


    🚀🚀首发:CSDN碰磕,学无止境


    🌞🌞🌞晴33°


    🎂🎂happy birthday to me.


    📅2022/6/25


    Mobx

    一款强大的状态管理工具

    🍰Mobx与redux的区别

    • mobx写法偏向与oop
    • 对一份数据可以直接进行修改操作,不需要始终返回一个新的数据
    • 并非单一store,可以多个
    • redux默认使用js原生对象存储数据,而mobx使用可观察对象

    🍰使用

    🍰🍰安装

    npm i mobx@5
    
    • 1

    使用严格模式

    configure({
        enforceActions:'always'
    })
    
    • 1
    • 2
    • 3

    🍰🍰observable&&autorun

    • autorun用于监听值的改变
    • observable用于定义
    import React,{Component} from 'react';
    import {observable,autorun} from 'mobx';
    
    /**
     * 基本类型
     */
    //对于普通类型数据的监听
    let observableNumber=observable.box(66)
    let observableDesc=observable.box("学无止境...")
    //第一次执行一次,之后被改变与它相关的会再次执行
    autorun(()=>{
      console.log(observableNumber.get())
    })
    setTimeout(() => {
      observableNumber.set(11)
      observableDesc.set("爱学.")
    }, 2000);
    
    /**
     * 对象使用map
     */
    let myobj=observable.map({
      name:"碰磕",
      age:9999
    })
    autorun(()=>{
      console.log("对象name属性改变了"+myobj.get("name"))
    })
    class Zhuye extends Component{
      render() {
        return (  
          <div>
            Mobx
          </div>
        );
      };
    };
    export default Zhuye;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38

    🍰🍰action

    专门修改可观察的value

    import {observable,autorun,action} from 'mobx'
    const store=observable({
        isTabbarShow:true,
        list:[],
        cityName:"北京",
        changeShow(){
            this.isTabbarShow=true
        },
        changeHide(){
            this.isTabbarShow=false
        }
    },{
        changeHide:action,
        changeShow:action//标记两个方法是action,专门修改可观察的value
    })
    export default store
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    然后在需要改变isTabbarShow的地方调用方法即可…

    🍰🍰🍰使用装饰器写法

    import {observable,autorun,action} from 'mobx'
    class Store{
        @observable isTabbarShow=true
        @observable list=[]
        @action changeShow(){
            this.isTabbarShow=true
        }
        @action changeHide(){
            this.isTabbarShow=false
        }
    }
    const store=new Store()
    export default store
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    由于不支持装饰器写法,需要让它支持

    • 1.安装依赖:
    npm i @babel/core @babel/plugin-proposal-decorators @babel/preset-env
    
    • 1
    • 2.创建.babelrc
    {
        "presets": [
            "@babel/preset-env"
        ],
        "plugins": [
            [
                "@babel/plugin-proposal-decorators",
                {
                    "legacy": true
                }
            ]
        ]
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 3.创建config-overrides.js
    const path = require('path')
    const { override, addDecoratorsLegacy } = require('customize-cra')
    
    function resolve(dir) {
        return path.join(__dirname, dir)
    }
    
    const customize = () => (config, env) => {
        config.resolve.alias['@'] = resolve('src')
        if (env === 'production') {
            config.externals = {
                'react': 'React',
                'react-dom': 'ReactDOM'
            }
        }
    
        return config
    };
    module.exports = override(addDecoratorsLegacy(), customize())
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 4.安装依赖
    npm i customize-cra react-app-rewired
    
    • 1
    • 5.修改package.json
    ----...
    "scripts": {
        "start": "react-app-rewired start",
        "build": "react-app-rewired build",
        "test":  "react-app-rewired test",
        "eject": "react-app-rewired eject"
      },
    ----....
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    vscode需要配置

    文件—首选项----设置-----搜索experimentalDecorators----勾上该设置

    最后重新运行即可…

    🍰🍰runInAction(异步)

    异步请求时需要,在严格模式下

    import axios from 'axios'
    import {observable,autorun,action,runInAction, configure} from 'mobx'
    configure({
        enforceActions:'always'
    })
    class Store{
        @observable isTabbarShow=true
        @observable list=[]
        @action changeShow(){
            this.isTabbarShow=true
        }
        @action changeHide(){
            this.isTabbarShow=false
        }
        @action getList(){
            axios({
                method:'GET',
                url:"https://m.maizuo.com/gateway?cityId=440300&ticketFlag=1&k=2005318",
                headers:{
                    "X-Client-Info": '{"a":"3000","ch":"1002","v":"5.2.0","e":"1654433035923688551579649"}',
                    "X-Host": "mall.film-ticket.cinema.list"
                }    
            }).then(res=>{
                runInAction(()=>{
                    this.list=res.data.data.cinemas
                })
            })
        }
    }
    const store=new Store()
    export default store
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    这样就可以修改this.list的了~

    Mobx的基本使用就大功告成了~生日快乐to me🤭

  • 相关阅读:
    Container is running beyond memory limits
    【分布式能源的选址与定容】基于非支配排序多目标粒子群优化算法求解分布式能源的选址与定容附Matlab代码
    利用原始套接字的抓包原理
    【网络协议】Http-下
    路由器二次开发一步一步把工业路由器变成一个高端的可指定出网、节点和链路的路由器,包含详细过程及快捷脚本(三)
    mybatis04关联关系映射
    索引【MySQL】
    Java常用设计模式
    Python 笔记(22)— 变量解析原则(LEGB)、浅拷贝、深拷贝
    计算机毕业设计(附源码)python学生宿舍管理系统
  • 原文地址:https://blog.csdn.net/m_xiaozhilei/article/details/125456832