Learn about the key concepts in redux with three images

Source: Internet
Author: User

Last week took an amateur time to see the redux, just beginning a little uncomfortable, a bit in the action, Reducer, store and middleware so many new concepts.

After some understanding, found that Redux's one-way data in the pattern is relatively easy to understand, combined with the redux one-way data flow model, many concepts are relatively clear.

The following redux in accordance with their own understanding of the relevant content, if you have just started to learn redux, hope to give you an intuitive understanding.

Action/reducer/store

First, take a look at the first diagram, which shows one-way data flow for redux and the three core concepts of action, reducer, and store.

The following is a description of the three concepts of action, reducer, and store.

Action and Action Creator

An action is an object that represents all the behavior that causes a state change (such as a response from a server, a user action on a page).

If we are going to implement a task management system, then the action object that adds the task will be the following form:

{    ' add_task ',    ' Read ES6 spec ',    ' Reading '}

The Action object is a description of the behavior and generally contains the following information:

    • A Type field of a string type that represents the action that will be performed
    • Additional data information that needs to be passed to the app (name and category in the example), data form users can customize

The action is created by the Action Creation function (action Creator) , and action Creator is a function that eventually returns an Action object.

For this behavior of adding tasks, the corresponding action creator is as follows:

function addtask (name, category) {    return  {        type:add_task,        name,        category    };}
Reducer

The action object simply describes the information about the behavior, and as to how to update state with a specific behavior, you need to look at reducer.

The simplest description of reducer is:

    • Reducer is a function
    • The function receives two parameters, an old state previousstate and an Action object
    • Returns a new state newstate

According to the above description, the REDUCER function can be represented as:

(previousstate, action) = NewState

The reducer function is usually in the following form:

function reducer (state = [], action) {    //  code switch for handling different action     (action.type) {        case  special_action:            //  according to Special_action Action UpdateState            //  returns the newstate        default:              Return  State    }}
Store

The actions describe the "what happened" fact, and reducers updates the state based on these actions, while the store is the object that the actions and reducers are connected to.

Store is the unified storage of data in Redux, maintaining all the state's content, so the main function of the store is:

    • Maintain the state content of your app
    • Provides the GetState () method to get the state
    • Provide the dispatch (action) method to update the state
    • Provides subscribe (listener) method Registration Listener

By looking at the method provided by the store, you can associate the action, reducer, and store together:

    1. Store receives a different action by using the dispatch (action) method
    2. Depending on the type and data information of the action object, the store object can update the state's contents through the REDUCER function

Middleware

Let's take a look at the second picture, which is not much different from the first one, but adds the middleware (middleware) to handle the action.

In Redux, the main function of Middlerwares is to handle the action in Action,redux must be a plain object. But to implement an asynchronous action or other function, the action might be a function, or a Promise object. This is where middleware help is needed to handle this particular action.

In other words, middleware in Redux will convert certain types of actions, so the last action passed to reducer must be the standard plain object.

The REUDX middleware can take different actions for the characteristics of the action:

    • You can choose to pass to the next middleware, such as: Next (action)
    • You can choose to skip some middleware, such as: dispatch (Action)
    • or more directly when the end of the pass, such as: return.

Middleware used in redux:

    • Redux-thunk:action can be a function to initiate an asynchronous request.
    • Redux-promise:action can be a promise object that is used to perform asynchronous operations more gracefully.
    • Redux-logger:action is a standard plain object used to record action and nextstate.

React-redux

After the introduction, we have seen some of the core concepts in redux. Redux and react no direct relationship, itself can support react, Angular, Ember and so on framework.

By React-redux This library, you can easily combine react and redux: react responsible for the page display, redux responsible for maintaining/updating the data status.

Here, the third picture shows how react-redux this library works, how react and redux are linked together.

The React-redux provides two key function modules provider and connect, these two modules guarantee the communication between react and redux, and see these two modules respectively.

Provider

As you can see through the provider code, provide is essentially a react component.

default class Provider extends Component {  getchildcontext () {    returnthis. Store}  }  Constructor (props, context) {    Super (props, context)    this. Store= Props.store  }  render () {    this. Props    return  children.only (children)  }}

The provider component mainly uses the react through the context property, the attribute (props) can be directly given to descendants component, without passing through the props layer, thereby reducing the component dependencies.

Connect

The main function of the Connect method is to make the component and store related, store data changes can timely notify the views re-rendering.

Any component processed through the Connect () function can get a dispatch method as the props of the component, as well as get all the content in the global state.

By source] You can see that after the Connect function runs, it returns a Wrapwithconnect function that receives a react component and then returns a processed connect component.

return functionWrapwithconnect (wrappedcomponent) {class Connect extends Component {constructor (props, context) {//get store from ancestral component       This. store = Props.store | |Context.store This. Stateprops = Computestateprops ( This. Store, props) This. Dispatchprops = Computedispatchprops ( This. Store, props) This. State = {storestate:NULL }      //merging Stateprops, Dispatchprops, Parentprops       This. Updatestate ()} shouldcomponentupdate (Nextprops, nextstate) {//component re-renders when data changes      if(propschanged | | mapstateproducedchange | |dispatchpropschanged) {         This. Updatestate (nextprops)return true}} componentdidmount () {//change the state of component         This. Store.subscribe (() = {           This. SetState ({storestate: This. Store.getstate ()}) })} render () {//generate a Package component connect        return (          <wrappedcomponent {... This. nextstate}/>)}} connect.contexttypes={Store:storeshape}returnConnect;} 

Detailed Content and demo

Many of the Redux concepts are simple introduction, more detailed introduction can refer to the contents of my collation, GitHub address:Wilbertian/stepbystep-redux

    • 01.action.md
    • 02.reducer.md
    • 03.store.md
    • 04.redux-data-flow.md
    • 05.Middleware (Part 1). MD
    • 05.Middleware (Part 2). MD
    • 06.react-redux.md

At the end of each article, there are some simple demo codes to help you understand what's going on in the article.

Summarize

This article combines three images to introduce some of the core concepts in redux, and the interaction between react and redux by React-redux this library.

More detailed content, has been collated on GitHub (Wilbertian/stepbystep-redux), through these presentations and the results of the demo, will be able to have a relatively basic understanding of Redux.

All the content is mainly referenced by the usage with React, and then added their own understanding to draw the above three graphs, while combining each concept to write some demos to help understand.

Learn about the key concepts in redux with three images

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.