redux 配置例子主要文件有javascript
configureStore.js --》 建立倉庫java
user.redux.js --》 redux相關信息(type,action,reducer )npm
reducers文件下的index.js --》 合併reducerredux
配置步驟 用npm 安裝 redux 和 wepy-redux babel
npm install redux --saveapp
npm install wepy-redux --saveless
代碼涉及修飾符 函數
配置修飾符插件(babel-plugin-transform-decorators-legacy)flex
npm install babel-plugin-transform-decorators-legacy --save-devthis
添加wepy.config.js 裏面 babel 的 plugins 的transform-decorators-legacy以下圖
項目src 目錄以下圖:
configureStore.js 代碼以下
import {createStore} from 'redux' import rootReducer from '../reducers' export default function configureStore(initialState) { const store = createStore(rootReducer, initialState) return store }
user.redux.js 以下
const AUTH_SUCCESS = 'LOGOUT_SUCCESS' // redux type const initState = { // 默認倉庫數據 isAuth: false, name: '' // 用戶名字 } export function userReducer(state = initState, action) { // userdeux 規則 switch (action.type) { case AUTH_SUCCESS: return {...initState, isAuth: true, ...action.payload} default: return state } } export function authSuccess(data) { // redux action return { type: AUTH_SUCCESS, payload: data } }
reducers文件下的index.js 代碼以下
import {combineReducers} from 'redux' import {userReducer} from '../reduxs/user.redux' const rootReducer = combineReducers({ // 合併規則 user: userReducer }) export default rootReducer
app.wpy 建立store 而且是設置 相關代碼以下
import {setStore} from 'wepy-redux' import configureStore from './store/configureStore' const store = configureStore() setStore(store)
pages 下面的 login.wpy 是用 redux 代碼以下
<style lang="less"> .user-container { display: flex; flex-direction: column; align-items: center; .user-form-btn { background: #ff4e00; color: #fff; } } </style> <template> <view class="user-container"> <view class="logo-img"></view> <text class="logo-text">當前用戶:{{$state.user.name}}</text> <view class="user-form"> <button @tap="loginHandle" class="user-form-item user-form-btn">登 錄</button> </view> </view> </template> <script> import wepy from 'wepy' import {authSuccess} from '../reduxs/user.redux' import {connect} from 'wepy-redux' @connect( (state) => { return state }, { authSuccess } ) export default class Login extends wepy.page { config = {} components = {} data = {} computed = {} methods = { loginHandle() { console.log(this.$state.user) this.methods.authSuccess({name:'登陸者名稱'}) } } events = {} onLoad() { } } </script>
實現過程圖片(從左到右):
點擊登陸觸發函數loginHandle 函數裏面執行了authSuccess 的action行爲從而改變了state user的name屬性
基於數據綁定 name顯示在view
下面是src 下面的文件打包