Redux Asynchronous Operation Learning Notes

Source: Internet
Author: User
Tags redux middleware

Summary:

Found in the study react ecological chain, react+react-router+webpack+es6+fetch and so on these are basically to understand the almost, can be applied to the actual combat, but this redux still can not, learn Redux also learned for a long time.

The longest thing that bothers me is the processing of redux asynchronous data streams. The main difficulty is the concept too much, contact the word too much , and the case of the Internet to see the head of pain, it is easy to faint, has been dizzy several times. Later I simplified, finally understand, haha. Come here, sum up today, hope to help you. However, if you are not familiar with Redux, you can look at an article I wrote earlier, if you are redux asynchronous operation http://www.cnblogs.com/xianyulaodi/p/5399264.html

1, Redux asynchronous process Introduction

Let's start with a picture first, about the asynchronous process of redux:

(Pictures from Baidu Pictures)

The approximate process is this:

Start with an action, and then through the middleware, why use middleware here, because the return value of dispatch can be a function. By Store.dispatch, the change of state is passed on to the store's younger brother, and Reducer,reducer is transferred to the new state, based on the action change. Finally all the changes are told to its eldest brother, the store. The store stores all the data and injects the data to the top of the component, so that the component can get the data it needs.

2. Demo Introduction

This demo is based on the website of the async adaptation, in fact, is to remove a lot of other distractions, let it just get an asynchronous request. Beginners, can be simple, simple, so more clear.

GitHub Address of original website: Https://github.com/lewis617/react-redux-tutorial/tree/master/redux-examples/async

I adapted the GitHub address: Https://github.com/xianyulaodi/reduxAsync

This article is also written through my own change. Can look at the code side to see this article, of course, some of the words are not very right, welcome to point out

The interface is as follows:

The interface is simple, that is, through an asynchronous request, the requested data is presented to the interface. Perhaps you would say, not just a request, what a big deal. But the request is to go through the process of redux, haha.

3. Code parsing

The following is a small parsing of the asynchronous process of redux. In the meantime also review some basic knowledge of redux.

3.1 first start with action, code in Action/index.js
1Import fetch from ' Isomorphic-fetch '2Export Const Receive_posts = ' receive_posts '3 4 //get news about successful action5 functionreceiveposts (Reddit, JSON) {6   return {7 type:receive_posts,8 Reddit:reddit,9Posts:json.data.children.map (Child =child.data)Ten   } One } A  - functionfetchposts (subreddit) { -  the   return function(Dispatch) { -      -     returnFetch (' http://Www.subreddit.com/r/${subreddit}.json ') -. Then (response =Response.json ()) +. Then (JSON = - Dispatch (Receiveposts (subreddit, JSON)) +       ) A   } at } -  - //start getting articles if you need to -Exportfunctionfetchpostsifneeded (subreddit) { -  -   return(Dispatch, getState) = { in  -       returnDispatch (Fetchposts (subreddit)) to  +     } -}

This request did not use Ajax, but the use of fetch, this a little bit to understand, the entry is relatively easy. Like the Redux asynchronous flowchart above, it needs a middleware middleware. In fact, the essence of async is in this middleware middleware here. Understand this, you can say the basic also understand the Redux asynchronous. So I will spend a lot of space to introduce this middleware.

What's the use of middleware? Why should we introduce it?

In Redux, the action is just a normal JS object (plain JavaScript objects) that carries the data. The value returned by action creator is an object of this action type. It is then distributed through Store.dispatch () ...

Action---> Dispatcher---> reducers

If you encounter an asynchronous situation, such as clicking a button, you want to update the view after 2 seconds to display the message "Hi". We might write this actioncreator:

var function (message) {    setTimeout(function  () {        return  {            ' SAY '),            message        }     )}

This will cause an error, because the Asyncsayactioncreator return is not an action, but a function. This return value cannot be recognized by reducer.

In other words, normally, the action returns an object, not a function. If a function is returned, an error occurs.

In the asynchronous operation, the return value of the action needs to be a function. So what to do, so need to introduce middleware middleware, which plays a role in the middle of the bridge, so that the return value of the action can be a function, so as to upload

Reducer there. That is, the middleware is used after the action is initiated, and the reducer is received before the time period.

It is also possible to say that middleware is primarily responsible for changing the dispatch method in the store so that it can handle different types of action inputs and get the final Javascript Plain object in the form of an action object.

Therefore, the above actioncreator can be rewritten as this: because the return value of the action is a function.

var function (message) {    returnfunction  (dispatch) {        setTimeout (function () {            dispatch ({                ' SAY ',                message            })            }}

How the Middleware Works

Middleware has a lot of middleware, but my case only refers to one of them, that is redux-thunk

Redux-thunk source code is as follows:

default function Thunkmiddleware ({dispatch, getState}) {  return next = action = =    typeof Action = = = ' function '?       Action (Dispatch, GetState):      Next (action);}

This means that if the action is a function, execute the action function, if it is not a function, execute the next function.

Specific principles can be seen in these two articles:

One of Redux learning: what is middleware?

Redux Middleware Detailed:Back to my project source code:
   fetchpostsifneeded here is a middleware. Redux-thunk intercepts the fetchpostsifneeded action, initiates a data request, and, if successful, passes the data to the action. thereby reaching reducer there.



Look again at the Reducer directory for Reducers/index.js

1Import {combinereducers} from ' Redux '2 Import {3 receive_posts4} from '. /actions '5 6 7 functionPosts (state = {8 items: []9 }, action) {Ten   Switch(action.type) { One  A      Casereceive_posts: -       //Object.assign is a grammar of ES6. Merge objects, merge objects into one, and the same as before, the latter covering the strong. Details can be seen here -       //https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign the       returnobject.assign ({}, state, { -Items:action.posts//the data exists here. -       }) -     default: +       return State -   } + } A  at //Discard, receive, start to accept the news, set the State.postsbyreddit as the relevant parameters - functionPostsbyreddit (state ={}, Action) { -   Switch(action.type) { -      Casereceive_posts: -       returnobject.assign ({}, state, { - [Action.reddit]: Posts (State[action.reddit], action) in       }) -     default: to       return State +   } - } the  * //combine all the reducer into one and pass it to the store $Const ROOTREDUCER =combinereducers ({Panax Notoginseng Postsbyreddit - }) the  +ExportdefaultRootreducer

This is similar to normal reducer. Determines the type of action, which returns different data based on the different types of action. The data is stored here in the items. There is only one reducer here. Finally combine into Rootreducer, pass to store.

Store/configurestore.js

1Import {createstore, applymiddleware} from ' Redux '2Import thunkmiddleware from ' Redux-thunk '3Import Createlogger from ' Redux-logger '4Import Rootreducer from '. /reducers '5 6Const CREATESTOREWITHMIDDLEWARE =Applymiddleware (7 Thunkmiddleware,8 Createlogger ()9 ) (CreateStore)Ten  OneExportdefault functionConfigurestore (initialstate) { AConst STORE =Createstorewithmiddleware (Rootreducer, initialstate) -  -   if(module.hot) { the     //Enable Webpack Hot module replacement for reducers -Module.hot.accept ('.. /reducers ', () = { -Const NEXTROOTREDUCER = require ('.. /reducers ') - store.replacereducer (nextrootreducer) +     }) -   } +  A   returnStore at}

How did we introduce Redux Thunk middleware in the dispatch mechanism?
We used the Applymiddleware (),
Const Createstorewithmiddleware = Applymiddleware (  thunkmiddleware,  Createlogger ()) (CreateStore)

Among them, Createlogger is a handy middleware for printing the action log. You can also return a function by using the specified Middleware,action creator in addition to returning the action object.

At this point, the action creator becomes the thunk.

take a look at the call on the interface: in Containers/app.js

Part of the code:

  // triggers after initialization of rendering   Componentdidmount () {    this. Props    //  can pass two values here, one is Reactjs one is Frontend    Dispatch (fetchpostsifneeded (' frontend ')  }

It is also necessary to pass the dispatch when changing the state.

Data is obtained through provider, which injects data from the store into the component. Make the top-level components available to their descendant component calls. The code is as follows:

import ' Babel-core/polyfill 'react ' react-dom' react-redux'./containers/ App './store/configurestore '= Configurestore () render (  <provider Store={store} >    <app/>  </provider>,  document.getElementById (' root '))

This completes the asynchronous operation of the redux. In fact, the main difference is also the action inside the middleware call, the other place is basically the same as the synchronous redux. Understand the middleware, basically understand the redux asynchronous

For Specific people still need to look at the source code and other appropriate article introduction. Of course, the demo is not perfect because of the lack of processing of request delivery failures and so on.

Attach a picture to end today's study notes:

Today's summary to here first, feel oneself summarizes a bit of chaos. Just recently with react wrote a small project, the next step will be asynchronous and synchronization, the real use of actual combat, then this blog to improve and supplement.

Because it is a beginner asynchronous operation, so there may be some areas of their own summary of the wrong. Mistakes, please note. If you have a lot of confused classmates about middleware, take a look at the links below.

Reference:

http://www.aliued.com/?p=3204

Http://www.cnblogs.com/bingooo/p/5500108.html#top

http://cn.redux.js.org/

1190000003746223

Https://zhuanlan.zhihu.com/p/20597452?utm_source=tuicool&utm_medium=referral

 

If you think the article is useful, you can also give a small red packet to encourage encouragement, haha

Redux Asynchronous Operation Learning Notes

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.