用法
安裝
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)
}
}
}))
複製程式碼