Story outline

Redux is a data management library with several important apis

  • getStateGets the state of the data
  • dispatchSend events to change the state
  • subscribeSubscribe to respond to view changes when state changes

Everything that changes state according to the rules is a pure function

Let’s write the Redux code by hand

Redux creates a store primarily through createStore

function createStore(){
    let currentState;
    let currentListeners = [];
    
    function getState(){
        return currentState
    }
    
    function dispatch(action){
        currentState = reducer(currentState,action)
        currentListeners.forEach( listener =>  listener())
    }
    
    function subscribe(listener){
        currentListeners.push(listener)
    }
    
    dispatch({ type: "initial" })
    
    return {
        getState,
        dispatch,
        subscribe
    }
}

Copy the code

Finally return a few methods

Middleware is used in REdux

createStore(countReducer,applyMiddleware(logger,thunk))
Copy the code

You can see that applyMiddleware handles redux middleware so let’s write this function

function applyMiddleware(... middlewares){ return function(createStore){ return function(reducer){ const store = createStore(reducer) let dispatch = store.dispatch; let midApi = { getState: store.getState, dispatch: (action,... args) => dispatch(action,... args) } let middlewareChain = middlewares.map( middleware => middleware(midApi) ) dispatch = compose(... MiddlewareChain)(store.dispatch)// Must be executed // The final enhanced dispatch looks like this return {... Store, dispatch}}}} // One of the basic operations of functional programming: function compose(... funcs) { if (funcs.length === 0) { return args => args; } if (funcs.length === 1) { return funcs[0]; } return funcs.reduce((a, b) => (... args) => a(b(... args))); } logger(thunk(dispath))Copy the code

Enhanced Dispatch

Executed at dispatch time in the pagelogger(thunk(dispatch))

How to write middleware

thunk

Function thunk({getState,dispatch}){return next => action => {console.log("******* execute thunk method **********") if(typeof action === 'function'){ return action(dispatch,getState) } return next(action) } }Copy the code

logger

Function logger ({getState} {return next = > action = > {the console. The log (" * * * * * * * to perform logger methods * * * * * * * * * * ") console.log("prevState",getState()) let resultReturn = next(action) console.log("prevState",getState()) return resultReturn } }Copy the code

You can see that logger(Chunk (dispatch)) executes its own method first and next() is the method below

Action = > {the console. The log (" * * * * * * * to perform thunk method * * * * * * * * * * ") if (typeof action = = = 'function') {return action (dispatch, getState)  } return next(action) }Copy the code

Then continue to execute thunk middleware and finally complete all middleware execution