Talking about the principle of Redux middleware

Source: Internet
Author: User
Tags redux middleware

When we use Redux to manage asynchronous data flow, we use middleware to redux-thunk middleware as an example, let's do a bit of analysis:

The first is to build the store, we need the following code to knead into the middleware similar to the construction of the Creatstore function:

Const Loggermiddleware == applymiddleware (  thunkmiddleware,  default  function  Configurestore (initialstate) {    return  createstorewithmiddleware ( Rootreducer, initialstate);}

In this piece of code, we use the

Applymiddleware function to knead the middleware into the factory function of the construction store,
The source code for the Applymiddleware function is as follows:
Import compose from './compose 'Exportdefault functionapplymiddleware (... middlewares) {return(createstore) = (reducer, initialstate, enhancer) {    varstore =CreateStore (reducer, initialstate, enhancer)varDispatch =Store.dispatchvarChain = []    varMiddlewareapi ={getState:store.getState, Dispatch: (Action)=Dispatch (Action)} chain= Middlewares.map (middleware =Middleware (MIDDLEWAREAPI)) Dispatch=Compose (... chain) (Store.dispatch)return{..... store, Dispatch}}}
first look at the return of the function, the Createstorewithmiddleware function we built through Applymiddleware is actually such a function

function (reducer, initialstate, enhancer) {      ...       return {          ..... store,          Dispatch     }}

And the store is the object that it came from.

The store's build process is basically like this, but at this point the store's dispatch method is not the original dispatch, note the following code:

Chain = Middlewares.map (middleware= Compose (... chain) (Store.dispatch)

This is the core of the Applymiddleware method, which processes each middleware and deposits it into the chain array, and then calls the Compose method to process the chain array, and the returned value is the dispatch of the store. The dispatch that we used in our business code

Next look at what the Compose method does:

default function Compose (... funcs  ) {if (funcs.length = = = 0) {    return arg = arg   Else {    = funcs[funcs.length-1]    = funcs.slice (0,-1)    return ( . args) = Rest.reduceright ((composed, f) = f (composed), Last (... args)  }}

It consolidates the various middleware by invoking the Reduceright method of the array

The first parameter of the Reduceright method is callback (Prevalue,curvalue), and the second parameter is to be passed to callback as the first parameter prevalue to use.

Then we go back to this code in the Applymiddleware method:

var middlewareapi = {      getState:store.getState,      = = Dispatch (action)    }    = middlewares.map (middleware = middleware (MIDDLEWAREAPI))

dispatch = Compose (... chain) (Store.dispatch)

Thus we can know that it is store.dispatch that passed to last (... args).

We can tell from the official documentation that the general structure of the middleware is as follows: (arrow function skipped here)

function Middleware ({dispatch, getState}) {    returnfunction  (next) {        return  function  (action) {            return  next (action);     }}}

The data structure inside the chain array is this: [function (next) {return function (action) {...}},function (next) {return function (action) {...}} ... ]

Which is the function of the inside layer of the middleware function.

function (next) {        returnfunction  (action) {            return  next (action);        }    }

And then through compose further reduceright refinement:

return (... args) = Rest.reduceright ((composed, f) = f (composed), Last (... args))

Compose is the function (action) {return next (action)}
The composed is still function (action) {return next (action), except that next is the return value of the previous middleware, traced back to the source, and next is actually store.dispatch all the way through F ( Composed) This way the middleware method rubs and comes in the variant dispatch

So the dispatch method of the store object returned by the CreateStore factory function that was rubbed into the middleware is actually function {return next action;}

Then the actual use of Redux-thunk for asynchronous data operation, thunk source code as follows:

functionCreatethunkmiddleware (extraargument) {return({dispatch, getState}) = next = action = {    if(typeofAction = = = ' function ') {      returnAction (Dispatch, GetState, extraargument); }    returnnext (action); };} Const Thunk=Createthunkmiddleware (); Thunk.withextraargument=Createthunkmiddleware;exportdefaultthunk;//arrow function Shift Normal, that's it .functionCreatethunkmiddleware (extraargument) {return function({dispatch, getState}) {return  function(next) {return function(action) {if(typeofAction = = = ' function ') {                 returnAction (Dispatch, GetState, extraargument); }               returnnext (action); }     }  };}

From the above analysis, our store.dispatch is this thing.

           function(action) {               if (typeof action = = = ' function ') {                  return Action (Dispatch, GetState, extraargument);               }                return next (action);            }

The action is written when we invoke the asynchronous fetch of the data:

function Fetchuri (key) {    returnfunction(dispatch) {        Dispatch (Request ("show" ));         return $.ajax ({            Url:BOOKLIST_REQ.uri,            dataType:"Jsonp",            data:{q:key,count:booklist_ Req.count}        ). Done (Res={            dispatch (receive (res));            Dispatch (Request ("hidden"))        . Fail (res=console.error (res));}    ;}

The excitation fetch asynchronous data method is Store.dispatch (Fetchurl ("xxx"));

So you don't have to elaborate on the back, how to execute it down at a glance

This is the whole middleware of the general work process, if there is anything to say the wrong place, you special to hit me Ah!

Talking about the principle of Redux middleware

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.