一個用于小程序和輕量級H5應用的狀態管理工具, 使用方法是一個簡化版本的Redux。之所以是適用于輕量級應用,主要是因為沒有實現組件間的數據共享。因此不適合于復雜,龐大的前端應用。
如果你也和我有同樣的困惑,那么你就該嘗試一下:
拷貝 /mp-redux/index.js文件到項目中引入即可。開包即用。
懶
const mpState = require('./mp-redux/index.js'); const userInfo = require('./model/userinfo.js'); const logs = require('./model/logs.js'); mpState.createStore({ logs, // 這些model 就是redux的reduce,必須是純函數,并且需要返回一個純對象 userInfo // 這些model 就是redux的reduce,必須是純函數,并且需要返回一個純對象 }, 'onShow') // 第二個參數是劫持的生命周期函數,這是為了解決不同平臺的差異性問題導致的。后期會考慮優化 復制代碼
// model 就是數據模型,是根據業務而來的 // model/userinfo.js const actions = require('./../action/logs.js'); // 這里同樣采用了redux的action機制 const initState = { logs: [] } module.exports = function (state = initState, action = {}) { const newState = { ...state }; switch (action.type) { case actions.addLogs: const now = new Date(); newState.logs.push({ time: now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds(), value: action.data }); return newState; case actions.clearLogs: newState.logs = []; return newState; default: return newState; } } // action/userinfo.js module.exports = { addLogs: 'LOGS_ADD', clearLogs: 'LOGS_CLEAR' } 復制代碼 |
// 使用connect來注入需要訂閱的狀態,并且mp-redux會在頁面對象中自動注入dispatch方法 const mpState = require('./../../mp-redux/index.js'); const util = require('../../utils/util.js'); const logActions = require('./../../action/logs.js'); Page(mpState.connect((state) => { return { userInfo: state.userInfo.userInfo, logs: state.logs.logs } }, { // 在這里所有的業務數據都保存在store中,所以頁面如果只有業務數據的話,是不需要data屬性的。 clearLogs() { this.dispatch({ // 通過dispatch方法來發出action,從而更新store中的數據 type: logActions.clearLogs }) } })) 復制代碼 |
// 不要吐槽,,,,,,我第一次寫測試用例。(-_-) const actions = require('./../action/logs.js'); const model = require('./../model/logs.js'); test('1. init logs data', () => { expect(model()).toEqual({ logs: [] }) }) test('2. add new log into empty logs', () => { const newState = model(undefined, { type: actions.addLogs, data: "Test new log" }); expect({ value: newState.logs[0].value, len: newState.logs.length }).toEqual({ value: "Test new log", len: 1 }); }) test('3. add new log into logs', () => { const newState = model({logs: [{time: '00:00:00', value: 'the first log'}]}, { type: actions.addLogs, data: "the second log" }); expect({ log1: newState.logs[0].value, log2: newState.logs[1].value, len: newState.logs.length }).toEqual({ log1: "the first log", log2: "the second log", len: 2 }); }) test('4. clear all logs', () => { const newState = model({ logs: [ { time: '00:00:00', value: 'log1' }, { time: '00:00:00', value: 'log2' } ] }, { type: actions.clearLogs }); expect({ len: newState.logs.length }).toEqual({ len: 0 }); }) 復制代碼 |
因為互聯網產品都是toC業務,UI基本上每天都在變化,但是業務的變化其實是很小的。我們通過將業務建模,在前端構建業務數據模型。而這些模型是可以預知的。因此也就可測試。
而對于一些互聯網產品,前端測試是一件非常繁瑣而復雜的事情。因此這個簡單的方案大大的降低了前端代碼變動引起的風險,而增加的工作量也并不是很大。可以一定程度上降低業務代碼的回歸測試成本。