wepy是引入wepy-redux的,但是他那种写法感觉不太好,所以自己参考vue中的vuex重写了。
使用会清晰很多。
1.store修改为以下结构
2.modules/carts.js
import { handleActions, createAction } from 'redux-actions'
import {getCarts} from '@/utils/api'
// 1.定义state
export const state = {
carts: []
}
// 2.定义reducers
// carts为区分reducers
export const cartsReducers = {
carts: handleActions({
['SET_CARTS'] (state,action){
return {
...state,
carts: action.payload
}
}
// 书写其他reducers
},state)
}
// 3.定义actions
// action中可以且只能在其中定义异步
export const cartsActions = {
FETCH_CARTS: createAction('SET_CARTS', () =>{
return new Promise(resolve => {
getCarts().then(res =>{
resolve(JSON.stringify(res))
})
})
})
// 书写其他actions
}
3.modules/global.js
import { handleActions, createAction } from 'redux-actions'
import {getCarts} from '@/utils/api'
// 1.定义state
export const state = {
num:0
}
// 2.定义reducers
export const globalReducers = {
global: handleActions({
['SET_NUM'] (state,action){
return {
...state,
num: action.payload
}
}
// 书写其他reducers
},state)
}
// 3.定义actions
export const globalActions = {
// 书写其他actions
}
4.modules/index.js
import { combineReducers } from 'redux'
import {globalReducers, globalActions} from './global'
import {cartsReducers, cartsActions} from './carts'
// 4.整合reducers
export const reducers = combineReducers({
...globalReducers,
...cartsReducers
})
// 5.整合actions
export const actions = {
...cartsActions,
...globalActions
}
5.index.js
import { createStore, applyMiddleware } from 'redux'
import promiseMiddleware from 'redux-promise'
import {reducers} from './modules'
// 6.redux的createStore创建store
export default function configStore () {
const store = createStore(reducers, applyMiddleware(promiseMiddleware))
return store
}
6.app.wpy(这个文件是没改动的,和wepy引用redux一样)
import { setStore } from 'wepy-redux'
import configStore from './store'
// 7.app.wpy中使用wepy-redux挂载
const store = configStore()
setStore(store)
7.使用页面
import {actions} from '../store/modules'
import {getCarts} from '@/utils/api'
console.log('moduleA ignored: ', moduleA) // => moduleA ignored: {}
// 8.使用
// 前面一个对象是定义state,后面定义actions
// 如果是直接操作reducers直接写对应的reducers名称,如:SET_NUM: 'SET_NUM'
@connect({
num (state) {
return state.global.num
},
carts(state){
return state.carts.carts
}
},{
FETCH_CARTS:actions.FETCH_CARTS,
SET_NUM: 'SET_NUM'
})
调用
// 9.调用
this.methods.SET_NUM(5)
this.methods.FETCH_CARTS()
到这里就结束了。