微信小程序状态管理的使用

安装:

npm install --save mobx-miniprogram mobx-miniprogram-bindings

创建store.js文件

// 创建 Store 实例对象
import { observable, action } from 'mobx-miniprogram'

export const store = observable({
  // 数据
  numA: 1,
  numB: 2,

  // 计算属性
  get sum () {
    return this.numA + this.numB
  },

  // action 函数,修改store中数据的值
  updateNum1: action(function(step) {
    this.numA += step
  }),
  updateNum2: action(function(step) {
    this.numB += step
  })
})

将页面、自定义组件和 store 绑定有两种方式: behavior 绑定 和 手工绑定 。

1. 手工绑定:

手工绑定 适用于全部场景。做法:使用 createStoreBindings 创建绑定,它会返回一个包含清理函数的对象用于取消绑定。

注意:在页面 onUnload (自定义组件 detached )时一定要调用清理函数,否则将导致内存泄漏!

import { createStoreBindings } from 'mobx-miniprogram-bindings'
import { store } from '../../store/store'

Page({
  data: {},
  onLoad() {
    this.storeBindings = createStoreBindings(this, {
      store,
      // 将仓库中的数据映射到当前页面this中
      fields: ['numA', 'numB', 'sum'],
      actions: ['updateNum1'],
    })
  },
  onUnload() {
    this.storeBindings.destroyStoreBindings()
  }
})

2. behavior 绑定

behavior 绑定 适用于 Component 构造器。做法:使用 storeBindingsBehavior 这个 behavior 和 storeBindings 定义段。

import { storeBindingsBehavior } from 'mobx-miniprogram-bindings'
import { store } from '../../store/store'

Component({
  behaviors: [storeBindingsBehavior],
  storeBindings: {
    // 数据源
    store,
    fields: {
      numA: 'numA',
      numB: 'numB',
      sum: 'sum'
    },
    actions: {
      updateNum2: 'updateNum2'
    }
  }
})

绑定配置

字段名类型含义
store一个 MobX observable默认的 MobX store
fields数组或者对象用于指定需要绑定的 data 字段
actions数组或者对象用于指定需要映射的 actions

fields

fields 有三种形式:

数组形式:指定 data 中哪些字段来源于 store 。例如 ['numA', 'numB', 'sum']
映射形式:指定 data 中哪些字段来源于 store 以及它们在 store 中对应的名字。例如 { a: 'numA', b: 'numB' } ,此时 this.data.a === store.numA this.data.b === store.numB
函数形式:指定 data 中每个字段的计算方法。例如 { a: () => store.numA, b: () => anotherStore.numB } ,此时 this.data.a === store.numA this.data.b === anotherStore.numB
上述三种形式中,映射形式和函数形式可以在一个配置中同时使用。

如果仅使用了函数形式,那么 store 字段可以为空,否则 store 字段必填。

actions

actions 可以用于将 store 中的一些 actions 放入页面或自定义组件的 this 下,来方便触发一些 actions 。有两种形式:

数组形式:例如 ['update'] ,此时 this.update === store.update
映射形式:例如 { buttonTap: 'update' } ,此时 this.buttonTap === store.update
只要 actions 不为空,则 store 字段必填。

延迟更新与立刻更新

为了提升性能,在 store 中的字段被更新后,并不会立刻同步更新到 this.data 上,而是等到下个 wx.nextTick 调用时才更新。(这样可以显著减少 setData 的调用次数。)

如果需要立刻更新,可以调用:

this.updateStoreBindings() (在 behavior 绑定 中)
this.storeBindings.updateStoreBindings() (在 手工绑定 中)

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

A_ugust__

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值