wepy裡推薦使用wepy-redux儲存全域變數
// app.wpy import { setStore } from 'wepy-redux' import configStore from './store' const store = configStore() setStore(store) //setStore是将store注入到所有页面中
// store文件夹下的index.js import { createStore, applyMiddleware } from 'redux' import promiseMiddleware from 'redux-promise' import rootReducer from './reducers' export default function configStore () { const store = createStore(rootReducer, applyMiddleware(promiseMiddleware)) //生成一个 store 对象 return store }
applyMiddleware函數的作用是對store.dispatch 方法進行增強和改造
這裡就是使用redux-promise來解決非同步
import { getStore } from 'wepy-redux' const store = getStore() // dispatch store.dispatch({type: 'xx', payload: data}) //xx是reducer名字 payload就是携带的数据 store.dispatch(getAllHoomInfo(store.getState().base)) //xx是action名字 //获取state const state = store.getState()
@connect({ data:(state) => state.base.data //注意这里是base下的state 所有要加上base. })
type
types裡是觸發action的函式名稱只是儲存函數名字依照模組去建立type.js
#
//base.js export const GETALLHOMEINFO = 'GETALLHOMEINFO'寫好了函數名稱在index.js中export出來
export * from './counter' export * from './base'
reducers
##隨著應用變得複雜,需要對reducer 函數進行拆分,拆分後的每一塊獨立負責管理state 的一部分這個時候多個模組的reducer透過combineReducers合併成一個最終的reducer函數,
import { combineReducers } from 'redux' import base from './base' import counter from './counter' export default combineReducers({ base, counter })
模組使用
handleActions
GETALLHOMEINFO reducer是將非同步action傳回的值賦值給data#
//base.js import { handleActions } from 'redux-actions' import { GETALLHOMEINFO } from '../types/base' const initialState = { data: {} } export default handleActions({ [GETALLHOMEINFO] (state, action) { return { ...state, data: action.payload } } }, initialState)
#actions
actions是對資料的處理export * from './counter' export * from './base'createAction用來建立Action的
import { GETALLHOMEINFO } from '../types/base' import { createAction } from 'redux-actions' import { Http, Apis } from '../../libs/interface' export const getAllHoomInfo = createAction(GETALLHOMEINFO, (base) => { return new Promise(async resolve => { let data = await Http.get({ url: Apis.ls_url + Apis.allHomeInfo, data: {} }) resolve(data)**//返回到reduer的action.payload** }) })###用法######
<script> import wepy from 'wepy' import { connect } from 'wepy-redux' import { getAllHoomInfo } from '../store/actions/base.js'// 引入action方法 import { getStore } from 'wepy-redux' const store = getStore() @connect({ data:(state) => state.base.data }) export default class Index extends wepy.page { data = { } computed = { } onLoad() { store.dispatch(getAllHoomInfo(store.getState().base)) } } </script>###推薦教學:《###微信小程式###》###
以上是小程式中wepy-redux的使用以及儲存全域變量的詳細內容。更多資訊請關注PHP中文網其他相關文章!