/** + Request information about the car + @param model - model of car + @param id - id of car **/functionrequestInfo(model, id) {return`${model} with id: ${id}`}/** + Buy the car + @param model - model of car + @param id - id of car **/functionbuyVehicle(model, id) {return`You purchased ${model} with id: ${id}`}/** + Arrange viewing for car + @param model - model of car + @param id - id of car **/functionarrangeViewing(model, id) {return`You have successfully booked a viewing of ${model} (${id})`}
/** + A generic execute function + Takes a receiver and a command **/exportdefaultfunctionexecute(receiver, command) {return receiver[command.action] && receiver[command.action](...command.params)}
现在我们无论在何时何地都可以执行这些命令了。
Make things happen | 让奇迹发生
import execute from'executor.js'import TeslaSalesControl from'receiver.js'// Arrange a viewingexecute(TeslaSalesControl, { action:'arrangeViewing', param: ['Model S','123'],})// Request Infoexecute(TeslaSalesControl, { action:'requestInfo', param: ['Model S Battery','123342'],})// Buy a Car!execute(TeslaSalesControl, { action:'buyVehicle', param: ['Tesla 3','23243425'],})
就是这样,现在让我们来对比一下 Redux!在 Redux 中:
The Store = The Receiver | Store 即接收器
Store 会根据 “reducers” 进行初始化,描述 Store 是如何变化的。这些 reducers 都是一些纯函数,每当被调用的时候都会返回一个新的 state,而不会导致莫名其妙地发生变化。这使得我们的代码具有高度的可预测性以及可测试性。
import { combineReducers } = 'redux';function arrangeViewing(state, action) { switch(action.type) { case "ARRANGE_VIEWING": const { model, id } = action.data; return `${model} and ${id}`default: return "" }}function requestInfo(state, action) { switch(action.type) { case "REQUEST_INFO": const { model, id } = action.data; return `${model} and ${id}`default: return "" }}function buyVehicle(state, action) { switch(action.type) { case "BUY_VEHICLE": const { model, id } = action.data; return `${model} and ${id}`default: return false }}const rootReducer = combineReducers({ arrangeViewing, requestInfo, buyVehicle});export default rootReducer;
import { applyMiddleware, createStore } from'redux'import createLogger from'redux-logger'import ReduxThunk from'redux-thunk'import rootReducer from'../imports/client/reducers/rootReducer'// create a loggerconstlogger=createLogger()constmiddleware= [ReduxThunk, logger]constStore=createStore(rootReducer, {},applyMiddleware(...middleware))exportdefault Store