• 【MobX集中状态管理工具】MobX真的取代了Redux吗


    前言

    博主主页👉🏻蜡笔雏田学代码
    专栏链接👉🏻React专栏
    之前学习了react-router-dom6版本的相关内容
    参考文章👉🏻【React Router 6 快速上手一】【React Router 6 快速上手二】
    今天来学习Mobx集中状态管理工具!
    感兴趣的小伙伴一起来看看吧~🤞

    在这里插入图片描述


    1. Mobx介绍

    一个可以和React良好配合的集中状态管理工具,和Redux解决的问题相似,都可以独立组件进行集中状态管理,mobx和react的关系,相当于vuex和vue。

    优势

    1. 简单:编写无模板的极简代码精准描述你的意图(原生js)
    2. 轻松实现最优渲染:依赖自动追踪,实现最小渲染优化
    3. 架构自由:可移植, 可测试 无特殊心智负担

    2. 配置开发环境

    Mobx是一个独立的响应式的库,可以独立于任何UI框架存在,但是通常大家习惯把它和React进行绑定使用,用Mobx来做响应式数据建模React作为UI视图框架渲染内容,我们环境的配置需要三个部分:

    1. 一个create-react-app创建好的React项目环境
    2. 引入mobx框架本身
    3. 一个用来连接mobx和React的中间件

    如何配置

    1️⃣使用create-react-app初始化react项目

    create-react-app react_mobx
    
    • 1

    2️⃣安装mobx和中间件工具mobx-react-lite(只能函数组件中使用)

    npm i mobx mobx-react-lite
    
    • 1

    3. 基础使用

    第一个store——需求: 使用mobx实现一个计数器的案例,点击加号按钮实现递增运算

    通过store(mobx)编写自增逻辑,数据管理,React Component实现事件绑定,数据渲染

    在这里插入图片描述

    初始化mobx

    初始化步骤:

    1. 定义数据状态(state)
    2. 在构造器中实现数据响应式处理
    3. 定义action函数(修改数据)
    4. 实例化store并导出实例

    src/store/counter.js

    // 编写第一个mobx store小案例
    import { makeAutoObservable } from 'mobx'
    class CounterStore {
      // 1.定义数据
      count = 0
      constructor() {
        // 2.把数据弄成响应式
        makeAutoObservable(this)
      }
      // 3.定义action函数(修改数据)
      addCount = () => {
        this.count++
      }
    }
    
    // 4.实例化,然后导出给react使用
    const counterStore = new CounterStore()
    export { counterStore }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    React使用store

    实现步骤:

    1. 在组件中导入counterStore实例对象
    2. 在组件中使用counterStore实例对象中的数据
    3. 通过事件调用修改数据的方法修改store中的数据
    4. 让组件响应数据变化

    src/App.js

    // 1.导入counterStore
    import { counterStore } from './store/counter'
    // 2.导入中间件observer方法,连接mobx和react,完成响应式变化
    import { observer } from 'mobx-react-lite'
    
    function App() {
      return (
        <div className="App">
          {/* 把store中的count渲染一下 */}
          {counterStore.count}
          {/* 点击事件触发action函数修改count值 */}
          <button onClick={counterStore.addCount}>+</button>
        </div>
      );
    }
    
    // 3.使用中间件包裹App让视图响应数据变化
    export default observer(App);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    4. 计算属性computed(衍生状态)

    概念:有一些状态根据现有的状态计算(衍生)得到,我们把这种状态叫做计算属性, 看下面的例子。

    在这里插入图片描述

    实现步骤

    1. 声明一个存在的数据
    2. 通过get关键词 定义计算属性
    3. 在 makeAutoObservable 方法中标记计算属性

    src/store/counter.js

    // 编写第一个mobx store小案例
    import { computed, makeAutoObservable } from 'mobx'
    class CounterStore {
      // 定义一个原始数据list
      list = [1, 2, 3, 4, 5, 6]
      constructor() {
        // 2.把count数据弄成响应式
        makeAutoObservable(this, {
          filterList: computed
        })
      }
      // 定义计算属性
      get filterList() {
        return this.list.filter(item => item > 2)
      }
      // 定义方法修改list
      addList = () => {
        this.list.push(7, 8, 9)
      }
    }
    
    // 4.实例化,然后导出给react使用
    const counterStore = new CounterStore()
    export { counterStore }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    src/App.js

    // 1.导入counterStore
    import { counterStore } from './store/counter'
    // 2.导入中间件连接mobx和react,完成响应式变化
    import { observer } from 'mobx-react-lite'
    
    function App() {
      return (
        <div className="App">
          {/* 使用计算属性 */}
          {counterStore.filterList.join('-')}
          <button onClick={counterStore.addList}>修改数组</button>
        </div>
      );
    }
    
    // 3.使用中间件包裹App
    export default observer(App);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    效果

    在这里插入图片描述

    5. 模块化

    场景:一个项目有很多的业务模块,我们不能把所有的代码都写到一起,这样很难维护,为了提供可维护性,需要引入模块化机制

    在这里插入图片描述

    实现步骤

    1. 拆分模块js文件,每个模块中定义自己独立的state/action
    2. 在store/index.js中导入拆分之后的模块,进行模块组合
    3. 使用React的useContext的机制导出useStore方法,供业务组件统一使用

    定义list模块

    import { makeAutoObservable } from 'mobx'
    
    class ListStore {
      List = ['react', 'vue']
      constructor() {
        makeAutoObservable(this)
      }
      addList = () => {
        this.List.push('angular')
      }
    }
    
    export { ListStore }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    定义counter模块

    // 编写第一个mobx store小案例
    import { computed, makeAutoObservable } from 'mobx'
    class CounterStore {
      // 定义一个原始数据list
      list = [1, 2, 3, 4, 5, 6]
      constructor() {
        // 2.把count数据弄成响应式
        makeAutoObservable(this, {
          filterList: computed
        })
      }
      // 定义计算属性
      get filterList() {
        return this.list.filter(item => item > 2)
      }
      // 定义方法修改list
      addList = () => {
        this.list.push(7, 8, 9)
      }
    }
    
    export { CounterStore }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    🔥重点:组合模块导出统一方法

    // 组合子模块
    // 封装统一导出的供业务使用的方法
    import React from 'react';
    import { CounterStore } from './counter';
    import { ListStore } from './list';
    
    // 1.声明一个rootStore
    class RootStore {
      constructor() {
        // 对子模块进行实例化操作
        // 将来实例化RootStore的时候,
        // RootStore有两个属性,分别是counterStore和listStore
        // 各自对应的值,就是我们导入的子模块实例对象
        this.counterStore = new CounterStore()
        this.listStore = new ListStore()
      }
    }
    
    // 实例化RootStore注入context
    const rootStore = new RootStore()
    // 使用react useContext机制,完成统一方法封装
    // 核心目的:让每个业务组件可以通过统一一样的方法获取store中的数据
    // Provider value={传递的数据}
    // 查找机制:useContext 优先从Provider里value找,如果找不到,就会找createContext方法传递过来的默认参数
    const context = React.createContext(rootStore)
    // 这个方法作用:通过useContext拿到rootStore实例对象,然后返回
    // 只要在业务组件中,调用useStore() -> rootStore实例对象
    const useStore = () => React.useContext(context)
    export { useStore }
    
    • 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

    组件使用模块中的数据:App.js

    import { observer } from 'mobx-react-lite'
    import { useStore } from './store/index'
    
    function App() {
      // 注意:解构赋值到store实例对象就可以了,防止破坏响应式
      // 用哪个store就解构哪个store
      // const {counterStore} = useStore() 
      const rootStore = useStore()
      console.log(rootStore)
      return (
        <div className="App">
          {rootStore.counterStore.list.join('-')}
        </div>
      );
    }
    
    // 3.使用中间件包裹App
    export default observer(App);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    6. 总结

    1️⃣初始化mobx的过程是怎样的?

    声明数据 => 响应式处理 => 定义action函数 => 实例化导出

    2️⃣mobx如何配合react,需要依赖什么包?

    mobx-react-lite作为连接包,导出observer方法,包裹组件(只能和函数组件配合)

    3️⃣模块化解决了什么问题?

    维护性问题

    4️⃣如何实现mobx的模块化?

    按照功能拆分store模块,根模块中组合子模块,利用context机制依赖注入

    今天的分享就到这里啦✨ \textcolor{red}{今天的分享就到这里啦✨} 今天的分享就到这里啦

    原创不易,还希望各位大佬支持一下 \textcolor{blue}{原创不易,还希望各位大佬支持一下} 原创不易,还希望各位大佬支持一下

    🤞 点赞,你的认可是我创作的动力! \textcolor{green}{点赞,你的认可是我创作的动力!} 点赞,你的认可是我创作的动力!

    ⭐️ 收藏,你的青睐是我努力的方向! \textcolor{green}{收藏,你的青睐是我努力的方向!} 收藏,你的青睐是我努力的方向!

    ✏️ 评论,你的意见是我进步的财富! \textcolor{green}{评论,你的意见是我进步的财富!} 评论,你的意见是我进步的财富!

  • 相关阅读:
    【从头构筑C#知识体系】2.2 分部类型
    .Net Core之选项模式Options使用
    RPM 与 DPKG 使用
    Boosting Few-Shot Visual Learning with Self-Supervision(代码理解)
    实际中常用的网络相关命令
    9.2.5.2 【MySQL】XDES 类型
    【rust】8、连接数据库:sqlx
    swift 问答app
    腾讯云精彩亮相 2023 长沙·中国 1024 程序员节,共创数智未来!
    如何用vue+免费的webdb 实现一个世界杯足球竞猜系统
  • 原文地址:https://blog.csdn.net/xuxuii/article/details/126414231