wechat-rematch 用于小程序的状态管理工具

用法

安装
npm install wechat-rematch
复制代码
使用
  • 小程序开发工具顶部工具栏:工具->构建npm

  • 小程序右侧工具栏:勾选“使用npm模块”

  • 参考以下demo,在代码中定义自己的models,用createStore组装所有models,按以下步骤改造app.js、Page、Component

定义models

models/count.js

  const count={
    state:{
      count:0
    },
    //处理直接修改state的事件
    reducers: {
      increment: (state, payload) => {
        return Object.assign(state, { count: state.count + payload })
      },
    },
    //处理事件
    effects: (dispatch) => ({ 
      async incrementAsync(payload, rootState) {
        await new Promise(resolve => setTimeout(resolve, 1000))
        dispatch.count.increment(payload)
      }
    })
  }
  module.exports  = count;
复制代码
生成store
const { createStore } = requirePlugin("wechat-rematch")
const count = require('./models/count')
const store = createStore({
  models:{
    count
  }
})
module.exports = store
复制代码
改造app.js
  const { Provider } = requirePlugin("wechat-rematch")
  const store = require('./store')
  App(
    Provider(store)({
      onLaunch: function () {
      }
    })
  )
复制代码
改造Page
const { connect } = requirePlugin("wechat-rematch")
//将count注入页面的data
function mapStateToData(state){
  return {
    count: state.count.count
  }
}
Page(connect(mapStateToData)({
  data:{

  },
  onLoad: function() {
   
    
  },
  add: function(){
    
    this.dispatch.count.increment(1)
  },
  addAsync: function(){
    this.dispatch.count.incrementAsync(1)
  }
}))
复制代码
改造Component

改造component和改造page完全相同

const { connect } = requirePlugin("wechat-rematch")
//将count注入组件的data
function mapStateToData(state) {
  return {
    count: state.count.count
  }
}
Component(connect(mapStateToData)({

  /**
   * 组件的方法列表
   */
  methods: {
    add:function(){
      console.log(this.data.count)
      this.dispatch.count.increment(1)
    }
  }
}))

复制代码

转载于:https://juejin.im/post/5c1735eee51d454902530a2f

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值