按照官方生成的wepy默認目錄是這樣的,如果不懂得如何生成wepy默認項目,請看這裏
介紹redux涉及到的幾個目錄
//types/counter.js 定義方法的名字
export const INCREMENT = 'INCREMENT'
export const DECREMENT = 'DECREMENT'
export const ASYNC_INCREMENT = 'ASYNC_INCREMENT'
//types/index.js 暴露counter.js裏面定義的方法名字
export * from './counter'
//reducers/counter.js 定義方法的名字
//通過handleActions函數導出
import { handleActions } from 'redux-actions'
//這裏把types裏的函數名引入 注意相對路徑
import { INCREMENT, DECREMENT, ASYNC_INCREMENT } from '../types/counter'
export default handleActions({
[INCREMENT] (state) {
//也可以在這個位置進行邏輯的處理之後再return處理之後的值,當然簡單的處理直接放return裏面處理也是可以的
return {
...state,
num: state.num + 1
}
},
[DECREMENT] (state) {
return {
...state,
num: state.num - 1
}
},
[ASYNC_INCREMENT] (state, action) {
return {
...state,
asyncNum: state.asyncNum + action.payload
}
}
}, {
num: 0,
asyncNum: 0
})
//reducers/index.js 定義方法的名字
import { combineReducers } from 'redux'
//函數裏面的counter使用的時候會用到
import counter from './counter'
export default combineReducers({
counter
})
上面默認生成的目錄都有,看懂即可,接下來是如何使用,上面已經定義了兩個狀態管理的值num和asyncNum:跟vuex也有類似的地方,redux這裏使用了connect連接器
//需要使用到num的某個頁面
<template>
<view>
<text> {{stateNum}} </text>
<text> {{asyncNum}} </text>
</view>
</template>
<script>
import wepy from 'wepy'
//引入connect連接器
import { connect } from 'wepy-redux'
//引入定義的方法
import { INCREMENT, DECREMENT } from '../store/types/counter'
import { asyncInc } from '../store/actions'
@connect({
stateNum (state) {
//這裏state後面的counter就是剛剛reducers/index.js裏面定義的名字
return state.counter.num
},
asyncNum (state) {
return state.counter.asyncNum
}
}, {
//這裏也可以用es6的語法簡寫
incNum: INCREMENT,
decNum: DECREMENT,
asyncInc
})
export default class Index extends wepy.page {
...
onLoad() {
//如果需要在這裏面調用incNum,而不是this.incNum()
this.methods.incNum();
//如果需要在這裏面使用num的值
this.stateNum;
console.log(this.stateNum);//先打印1,後打印2---執行了兩遍onLoad
}
}
</script>
官網https://github.com/sysuzjz/wepy-store
參考https://www.jianshu.com/p/cc9a78d091e7