200行代码写一个简易的dva

在美团实习的时候,第一次接触到dva这样的react框架,回学校的时候,就想有机会本身实现一下这样的框架,虽然本身水平有限,可是能够试一试哈。 目标是实现dva model的同步和异步 dispatch action。react

看看 dva 的构成redux

let counterModel = {
	 namespace: 'counter',
	 state: {
	    num: 0
	 }
	 
	 reducers: {
	     add(state, action){
	         return {
            		num: state.num + 1
            }	
	     }
	 }
	}
复制代码

对state的更新缓存

var app = new dva();
app.model(counterModel);
app.start();
app._store.dispatch({
	type: 'counter/add'
});
复制代码

上述就是 dva 对 state 的更新, 经过dispatch {type: A / B} 其中 A 是指 model的 namespace, B 是指 model 中 reducers 具体的reducer方法。app

其中 dva 对异步的处理是用 redux-saga 处理的,由于做者并不熟悉redux-saga,拿 redux-thunk 代替了。框架

好,咱们开工了

  • 第一步 建立store异步

    const createStore = (reducer, initialState) => {
      let currentReducer = reducer;
      let currentState = initialState;
      let listener = () => { };
    
      return {
          getState() {
              return currentState;
          },
          dispatch(action) {
              let {
                  type
              } = action;
              currentState = currentReducer(currentState, action);
              listener();
              return action;
          },
          subscribe(newListener) {
              listener = newListener;
          }
      }
      } 
    复制代码

store 主要是 存储数据,开放state更新接口。async

  • 第二步 引入中间件 applyMiddleware函数

    const compose = (...funcs) => {
     if (funcs.length === 0) {
         return arg => arg
     }
    
     if (funcs.length === 1) {
         return funcs[0]
     }
    
     const last = funcs[funcs.length - 1]
     const rest = funcs.slice(0, -1)
     return (...args) => rest.reduceRight((composed, f) => f(composed), last(...args));
     }
    
    
     const applyMiddleware = (...middlewares) => {
         return (createStore) => (reducer, initialState, enhancer) => {
             var store = createStore(reducer, initialState, enhancer)
             var dispatch = store.dispatch;
             var chain = [];
             var middlewareAPI = {
                 getState: store.getState,
                 dispatch: (action) => store.dispatch(action)
             }
             chain = middlewares.map(middleware => middleware(middlewareAPI))
             dispatch = compose(...chain)(store.dispatch)
             return {
                 ...store,
                 dispatch
             }
         }
     }
    复制代码

redux 中间件 洋葱模型,修改了dispatch 方法。学习

  • 引入异步中间件redux-thunk和logger中间件测试

    const logger = store => next => action => {
        console.log('prevState', store.getState());
        let result = next(action);
        console.log('nextState', store.getState());
        return result;
    	};
    
    	const thunk = ({
    	    dispatch,
    	    getState
    	}) => next => action => {
    	    if (typeof action === 'function') {
    	        return action(dispatch, getState);
    	    }
    	    return next(action);
    	}
    复制代码

    这里引入 redux-thunk 作异步处理。

  • 加入测试model

    let counterModel = {
    
      namespace: 'counter',
    
      state: {
          num: 0
      },
    
      reducers: {
          add(state, action) {
              console.log('reducer add executed');
              return {
                  num: state.num + 1
              }
          },
          asyncAdd(state, action) {
              console.log('reducer asyncAdd executed');
              return {
                  num: state.num + 1
              }
          },
          test(state, action) {
              console.log('reducer test executed');
              return {
                  state
              }
          }
      }
      };
    
      let userModel = {
      
      namespace: 'user',
    
      state: {
          name: 'xxxx'
      },
    
    
      reducers: {
          modify(state, {
              payload
          }) {
              console.log('reducer modify executed');
              let {
                  name
              } = payload
              return {
                  name
              }
          }
      }
      };
    复制代码
  • 对不一样model下的reducer进行分发

    const combineReducer = (reducers) => (state = {}, action) => {
      let {
          type
      } = action;
      let stateKey = type.split('/')[0];
      let reducer = type.split('/')[1];
    
      reducers.map((current) => {
          if (current.name === reducer) {
              state[stateKey] = current(state[stateKey], action);
          }
      });
    
      return state;
      }
    复制代码

    这里由于 combineReducer 是 reducer的总入口,在这里根据action 的 type 转发到具体model下的reducer方法

  • dva 构造函数

    class dva {
          constructor() {
              this._models = [];
              this._reducers = [];
              this._states = {};
          }
          model(model) {
              this._models.push(model);
          }
          start() {
              for (var i = 0; i < this._models.length; i++) {
                  this._states[this._models[i].namespace] = {
                      ...this._models[i].state
                  };
                  Object.keys(this._models[i].reducers).map((key) => {
                      if (this._models[i].reducers.hasOwnProperty(key)) {
                          this._reducers.push(this._models[i].reducers[key]);
                      }
                  })
      
              }
              var rootReducer = combineReducer(this._reducers);
              let createStoreWithMiddleware = applyMiddleware(thunk, logger)(createStore);
              this._store = createStoreWithMiddleware(rootReducer, this._states);
              this._store.subscribe(() => {
                  console.log(this._store.getState());
              })
          }
      }
    复制代码

    dva 构造方法主要工做是缓存model,建立store。

测试数据

var app = new dva();
app.model(counterModel);
app.model(userModel);

app.start();
app._store.dispatch({
    type: 'counter/add'
});

app._store.dispatch({
    type: 'user/modify',
    payload: {
        name: 'shadow'
    }
})

app._store.dispatch((dispatch, getState) => {
    setTimeout(() => {
        dispatch({
            type: 'counter/asyncAdd'
        })
    }, 5000);
})
复制代码

控制台的输出

一点留言

这个固然是最粗糙的dva部分实现了,由于自己本身并无去看dva源码,只是看了dva API 蒙头实现下,其中已经有不少很优秀的redux周边生态,例如redux-thunk,logger等。固然也是复习了一下部分redux源码了,看成本身学习的一个阶段学习吧,最后像dva做者 陈谦 致敬。

最后留个地址吧:

http://oymaq4uai.bkt.clouddn.com/index.js

相关文章
相关标签/搜索