在微信小程式中使用redux
ofollow,noindex" target="_blank">DEMO
需要解決的問題
- 如何在小程式中引入redux狀態管理庫,及它相關的外掛?
- 微信小程式沒有清晰的非同步api,便於thunkMiddleware處理非同步請求(非同步操作),如何解決?
- 如何正確使用store的三大核心方法(
getStore
dispatch
subscribe
)?
redux並不是react專屬,所以他可以在任何地方使用,小程式也不例外。解決上面三個問題就可以了。
問題一: 如何在小程式中引入redux狀態管理庫,及它相關的外掛?
- 使用
npm
在臨時目錄裡安裝redux
和其他你需要用到的包,如:logger
thunkMiddleware
。這裡以redux示例。 - 進入
node_module
中,拷貝如下檔案:\redux\dist\redux.js
或者\redux\dist\redux.min.js
- 根據1/2中的步驟。把
redux.js
logger.js
thunkMiddleware
都拷貝到小程式專案資料夾\module
目錄下,沒有請新建。
問題二: 微信小程式沒有清晰的非同步api,便於thunkMiddleware處理非同步請求(非同步操作),如何解決?
前面有文章已經寫過,如何將微信非同步api轉換為Promise,便於非同步程式設計: 把微信小程式非同步API轉為Promise,簡化非同步程式設計
讀完會,把 to-promise
庫和 redux
一樣放在 \module
資料夾下
問題三:如何正確使用store的三大方法( getStore
dispatch
subscribe
)?
這也是最關鍵的
在 app.js
中建立 store
//app.js import reducer from './reducer/index' import { createStore, applyMiddleware } from './module/redux' import logger from './module/redux-logger' import thunkMiddleware from './module/redux-thunk' //建立redux store export const store = createStore( reducer, applyMiddleware( logger,//用於控制檯state除錯 thunkMiddleware//用於處理非同步action ) ) App({ //... })
編寫 action
// 專案根目錄/action/http3Steps.js export const REQUSET_BEGIN = 'REQUEST_BEGIN' export const RECEIVED = 'RECEIVED' export const REQUEST_FAILED = 'REQUEST_FAILED' //建立三個請求http事務時的狀態action,用於處理通用http請求 //1 請求開始;2 收到請求;3 請求失敗 export const requestBegin = (requestName) => ({ type: REQUSET_BEGIN + requestName }) export const received = (requestName, res) => ({ type: RECEIVED + requestName, res }) export const requestFailed = (requestName, err) => ({ type: REQUEST_FAILED + requestName, err })
編寫索引action:
// 專案根目錄/action/index.js import { requestBegin, received, requestFailed } from './http3Steps' import toPromise from '../module/to-promise' //微信小程式沒有提供Promise版本的非同步api //我封裝了一個庫,把微信小程式非同步api轉化為Promise,用於處理redux中的非同步action //專案地址:https://github.com/tornoda/to-promise //使用方法見blog:https://www.cnblogs.com/looyulong/p/9471424.html const toPromiseWx = toPromise(wx) const request = toPromiseWx('request') //這是一個同步的action export const INCREASE = 'INCREASE' export const increase = { type: INCREASE } //這是一個非同步action //網路請求action //根據redux官網的介紹,它應該是一個Promise,但是微信小程式沒有提供Promise版本的非同步api,需要使用上面提到的工具庫 export const GAME_LIST = '_GAME_LIST' export const fetch = (requestName, option) => { return (dispatch) => { dispatch(requestBegin(requestName))//請求開始,更新state狀態 return request(option) .then( (res) => { dispatch(received(requestName, res)); return res },//請求成功,把返回的資訊在state中更新 (err) => { dispatch(requestFailed(requestName, err)) }//請求失敗,把失敗的資訊在state中更新 ) } }
編寫處理action的reducer
// 專案根目錄/reducer/index.js import { INCREASE } from '../actions/index' import { GAME_LIST } from '../actions/index' import { REQUSET_BEGIN, RECEIVED, REQUEST_END } from '../actions/http3Steps' import { combineReducers } from "../module/redux"; //這是處理本例子中同步action的reducer export const disposeIncrease = (state = 0, action) => { switch (action.type) { case INCREASE: console.log('redux is worked') return state + 1 default: return state } } //這是處理本例中非同步的reducer const preState = {} export const disposeFetch = (state = preState, action) => { switch (action.type) { case REQUSET_BEGIN + GAME_LIST: return { ...state, status: 'REQUEST_BEGIN', } case RECEIVED + GAME_LIST: return { ...state, status: 'RECEIVED', res: action.res } case REQUEST_END + GAME_LIST: return { ...state, status: 'REQUEST_END', err: action.err } default: return state } } //按照state的結構組合起來 export default combineReducers({ theIncreasingNo: disposeIncrease, asyncData: disposeFetch })
讓state變化時自動更新ui檢視
方法很簡單,在 page
的 index.js
中的 onLoad
函式裡面呼叫 store.subscribe()
方法監聽區域性data.
onLoad: function () { const _this = this //在onLoad函式中訂閱state的更新 //如果state變化,對應ui就會更新 subscribe(() => { const { asyncData: { status }, theIncreasingNo } = getState() _this.setData({ syncData: ` 請求狀態:${status}, 返回的資料請檢視控制檯 `, number: theIncreasingNo }) }) }
觸發動作,發出action,改變state
//index.js import { store } from '../../app' import { increase, fetch, GAME_LIST } from '../../actions/index' const { dispatch, subscribe, getState } = store Page({ data: { syncData: 'Hello World', number: '0', }, onLoad: function () { const _this = this //發出一個非同步action dispatch(fetch(GAME_LIST, { url: 'http://open.douyucdn.cn/api/RoomApi/game' })).then((data) => { console.log(data) }) //在onLoad函式中訂閱state的更新 //如果state變化,對應ui就會更新 subscribe(() => { const { asyncData: { status }, theIncreasingNo } = getState() _this.setData({ syncData: ` 請求狀態:${status}, 返回的資料請檢視控制檯 `, number: theIncreasingNo }) }) }, testSyncAction: function () { //發出一個同步action dispatch(increase) } })
如下圖:
原始檔
實戰專案
稍後上傳,敬請期待。