Mobx

7/17/2020 react

# 1.Mobx介绍


一个可以和React良好配合的集中状态管理工具,和Redux解决的问题相似,都可以独立组件进行集中状态管理

优势

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

# 2. 配置开发环境


Mobx是一个独立的响应式的库,可以独立于任何UI框架存在,但是通常大家习惯把它和React进行绑定使用,用Mobx来做响应式数据建模,React作为UI视图框架渲染内容,我们环境的配置需要三个部分 一个create-react-app创建好的React项目环境 mobx框架本身 一个用来链接mobx和React的中间件

安装

// 创建项目
create-react-app react-mobx-code
// 安装mobx和中间件工具 mobx-react-lite  只能函数组件中使用
yarn add mobx mobx-react-lite
1
2
3
4

# 3. 基础使用


1. 初始化mobx

  1. 定义数据状态
  2. 在构造器中实现数据响应式处理
  3. 定义action函数
  4. 实例化store并导出
// 使用class 类实现
import { makeAutoObservable } from 'mobx'
// 定义类
class CounterStore {
  // 1. 初始化数据
  count = 0
  constructor() {
    // 2. 把数据转换成响应式
    makeAutoObservable(this)
  }
  // 3. 定义action函数 修改数据
  addCount = () => {
    this.count++
  }
}
// 4. 实例化 然后导出
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. 在组件中使用storeStore实例对象中的数据
  3. 通过事件调用修改数据的方法修改store中的数据
  4. 让组件响应数据变化
// 1. 导入store 
import { counterStore } from './store/counter'
// 2. 导入中间件 连接 mobx react 完成响应式
import { observer } from 'mobx-react-lite'
function App () {
  const { count, addCount } = counterStore
  return (
    <div className="App">
      {/* 渲染数据 */}
      <h1>{count}</h1>
      {/* 触发action事件 */}
      <button onClick={addCount}>更新</button>
    </div>
  )
}
// 让组件和store响应式化
export default observer(App)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

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


  1. 生命一个存在的数据
  2. 通过get关键词 定义计算属性
  3. 在 makeAutoObservable 方法中标记计算属性
// 使用class 类实现
import { makeAutoObservable } from 'mobx'
// 定义类
class ListStore {
  // 1. 初始化数据
  list = [1, 2, 3, 4, 5, 6]
  constructor() {
    // 2. 把数据转换成响应式
    makeAutoObservable(this)
  }
  get filterList () {
    return this.list.filter(item => item > 2)
  }
  // 3. 定义action函数 修改数据
  addList = () => {
    this.list.push(7, 8, 9)
  }
}
// 4. 实例化 然后导出
const listStore = new ListStore()
export { listStore }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// 1. 导入store 
import { listStore } from './store/counter'
// 2. 导入中间件 连接 mobx react 完成响应式
import { observer } from 'mobx-react-lite'
function App () {
  const { list, addList, filterList } = listStore
  return (
    <div className="App">
      {/* 渲染数据 */}
      <h1>原始数据:{list.join('-')}</h1>
      <h1>计算数据:{filterList.join('-')}</h1>
      {/* 触发action事件 */}
      <button onClick={addList}>更新</button>
    </div>
  )
}
// 让组件和store响应式化
export default observer(App)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# 5. 异步数据处理


import { makeAutoObservable, runInAction } from 'mobx'
class AsyncStore {
  data = []
  constructor() {
    makeAutoObservable(this)
  }
  getData = () => {
    setTimeout(() => {
      runInAction(() => {
        this.data = [
          {
            name: 'Dom',
            id: 1
          },
          {
            name: 'Tom',
            id: 2
          }
        ]
      })
    })
  }
}
export { AsyncStore }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import React from 'react'
import { CounterStore } from './counter.Store'
import { ListStore } from './list.Store'
import { AsyncStore } from './async.Store'
// 申明一个RootStore  类函数
class RootStore {
  constructor() {
    // 把子模块的实例挂载到RootStore上
    this.listStore = new ListStore()
    this.counterStore = new CounterStore()
    this.asyncStore = new AsyncStore()
  }
}
// 实例化根store
const rootStore = new RootStore()
// Provider value = {传递的数据}
// 查找机制: useContext 优先从Provider value 去查找,找不到--> 就会去找createContext方法传递过来的默认值
const context = React.createContext(rootStore)
// 通过useContext拿到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
import { useEffect, useRef } from 'react'
// 1. 导入store 
import { useStore } from './store/index'

// 2. 导入中间件 连接 mobx react 完成响应式
import { observer } from 'mobx-react-lite'
function App () {

  const { listStore, counterStore, asyncStore } = useStore()
  const renderRef = useRef(true)
  useEffect(() => {
    if (renderRef.current) {
      renderRef.current = false
      return
    }
    asyncStore.getData()
  }, [])

  return (
    <div className="App">
      <h1>count: {counterStore.count}</h1>
      <button onClick={counterStore.addCounter}>修改</button>
      <hr />
      <h1>list:{listStore.list.join('-')}</h1>
      <h1>list:{listStore.filterList.join('-')}</h1>
      <button onClick={listStore.addList}>修改</button>
      <hr />
      {
        asyncStore.data.map(item => <h2 key={item.id}>{item.name}</h2>)
      }
    </div>
  )
}
// 让组件和store响应式化
export default observer(App)

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

# 6. 模块化


counter.Store.js

import { makeAutoObservable } from "mobx"
class CounterStore {
  count = 0
  constructor() {
    makeAutoObservable(this)
  }
  addCounter = () => {
    this.count++
  }
}
export { CounterStore }
1
2
3
4
5
6
7
8
9
10
11

list.Store.js

// 使用class 类实现
import { makeAutoObservable } from 'mobx'
// 定义类
class ListStore {
  // 1. 初始化数据
  list = [1, 2, 3, 4, 5, 6]
  constructor() {
    // 2. 把数据转换成响应式
    makeAutoObservable(this)
  }
  get filterList () {
    return this.list.filter(item => item > 2)
  }
  // 3. 定义action函数 修改数据
  addList = () => {
    this.list.push(7, 8, 9)
  }
}
// 4. 实例化 然后导出
export { ListStore }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

index.js

import React from 'react'
import { CounterStore } from './counter.Store'
import { ListStore } from './list.Store'
// 申明一个RootStore  类函数
class RootStore {
  constructor() {
    // 把子模块的实例挂载到RootStore上
    this.listStore = new ListStore()
    this.counterStore = new CounterStore()
  }
}
// 实例化根store
const rootStore = new RootStore()
// Provider value = {传递的数据}
// 查找机制: useContext 优先从Provider value 去查找,找不到--> 就会去找createContext方法传递过来的默认值
const context = React.createContext(rootStore)
// 通过useContext拿到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

App.js

// 1. 导入store 
import { useStore } from './store/index'

// 2. 导入中间件 连接 mobx react 完成响应式
import { observer } from 'mobx-react-lite'
function App () {

  const { listStore, counterStore } = useStore()
  return (
    <div className="App">
      <h1>count: {counterStore.count}</h1>
      <button onClick={counterStore.addCounter}>修改</button>
      <hr />
      <h1>list:{listStore.list.join('-')}</h1>
      <h1>list:{listStore.filterList.join('-')}</h1>
      <button onClick={listStore.addList}>修改</button>
    </div>
  )
}
// 让组件和store响应式化
export default observer(App)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

# Mobx基础使用 - 总结

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

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

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

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

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

维护性问题

4. 如何实现mobx的模块化?

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

更新: 8/22/2022, 11:08:23 AM