Redux and Pure JS get started with the example explained

Source: Internet
Author: User
redux and Pure JS get started with the example explained

Learning redux may be a nightmare, I guess everyone should have read the article "You might not Need redux" and then threw away the computer in hand. If it's npm install--save React-redux, you're probably not quite sure what Redux is doing, or not so clear, after a few todolist routines. Perhaps all you need is a redux example that does not contain react. What's the relationship between Redux and react?

There is no relationship between react and redux.

Redux supports react, angular, ember, jquery, and pure JS. The redux and react frameworks work well together, but it doesn't mean that the first step in learning Redux is to install the React binding library:

NPM Install--save React-redux

May first look at the redux of pure JS support more conducive to understanding redux. preparatory work

Preparation is simple, you don't need to install any dependencies, you don't need package management tools, you don't need module packaging tools, and you don't even need modules at all.

To open your favorite text editor, paste the HTML code below.

<! DOCTYPE html>

The precompiled Redux file is introduced here through the <script src= "Https://unpkg.com/redux@latest/dist/redux.min.js" ></script>.

Open the above HTML file directly in the browser and then pass the global Variable window in the console. Redux can access the Redux object.

You can see its object methods:

a simple example

Perfect the following code in the HTML code above, a simple redux example is done.

<! DOCTYPE html>  

Now open the above HTML file in the browser and try clicking on the button inside. This is the use of Redux in native JS. Redux Basic Concepts

The following is a simple example to illustrate several basic concepts in redux. 1. Single Data source

There is only a single data source in the Redux, and all the state of the application is stored in a single object. In this case, we maintain only one state, which is the color property of the <span id= "Colorel" >watch my color.</span>, so there is only one property in the object:

var initalstate = {
  color: ' Red '
}

This is the simplest example, when the application becomes complex, we need to first design the structure of the object according to all the state considerations of the application, but here we are not concerned about the problem for the time being. 2, use action to change the application of state

When we need to change the state of the application, we cannot directly modify the state value, the state in the Redux is read-only.

The only way to change the state is to trigger a action,action is an ordinary JavaScript object that describes what happened. Each action object must have a type attribute, which you can understand to be the only name that identifies the action.

In this case, we give the three buttons #red, #green, #toggle分别绑定了click事件, each time we click to trigger an action, notice the following parts of the code:

Store.dispatch ({
    type: ' RED '
})

Store.dispatch ({
    type: ' GREEN '
})

Store.dispatch ({
    type: ' TOGGLE '
})

Three objects were passed in the Store.dispatch method (which explains what Store.dispatch is)

{type: ' RED '}

{type: ' GREEN '}

{type: ' TOGGLE '}

Is that Action,type is the only name that identifies their type. The action is an object that describes what happened, and the above 3 action can be understood as "red", "green" or "switch colors". 3, the use of reducer to perform the modification of the state

The action is an ordinary JavaScript object that describes what happened, but it does not describe how this happens to modify state, and how it is reducer to modify it according to the action.

What is reducer is a pure function that receives the old State and the action as an input parameter and returns the new state.

In this case, this is the following function:

function color (State, action) {
    if (typeof state = = ' undefined ') {return
        initialstate
    }

    switch ( Action.type) {case
        ' red ': Return 
            {color: ' red '} case
        ' green ': Return 
            {color: ' green '}
        Ggle ': return
            state.color = = ' Red '? {color: ' green '}: {color: ' red '}
        default: Return state
    }
}

Reducer determines how to modify state and returns a new state where the action's type is ' red ' where the value of the Color property is ' red ' when the action type is ' GREEN ' When you return to a new state where the value of the color attribute is ' green ', ' TOGGLE ' is the same.

About Reducer Note: Do not modify the value of state, please return a new copy; When you encounter an unknown action, you must return to the old state by default;

Also, please note that the {type: ' Red '} object above is semantically <span id= "Colorel" >watch my color!</span>, but understand that this is just the meaning of the language, As for how this action is handled by reducer, you can of course <span id= "Colorel" >watch my color!</span> when triggering {type: ' RED '} Turn green or even erase. Keep in mind that the action simply describes what happened and Reducer decides what to do with the action. 4, store

The store is an object that is generated using the CreateStore method provided by Redux, and we need to pass reducer as a parameter, in this case:

Reducer
function Color (state, action) {
    if (typeof state = = ' undefined ') {return
        initialstate
    }

    switch (action.type) {case
        ' red ': Return 
            {color: ' red '} case
        ' green ': Return 
            {color: ' green '}
  case ' TOGGLE ': return
            state.color = = = ' Red '? {color: ' green '}: {color: ' red '}
        Default: Return '} '

var store = Redux.createstore ( Color

The store has the following methods:

The Store.getstate () method is used to get state, to update the state through the Store.dispatch (action) method, to register the listener through the subscribe (listener) method, and to execute the function automatically upon change;

In this example:

Gets state by Store.getstate () and sets the color properties of the Colorel based on the state value:

function Rendervalue () {
    colorEl.style.color = store.getstate (). Color
}

Register the Listener by Store.subscribe () to perform the above function whenever the state changes:

Registered Listener
store.subscribe (rendervalue)

by Store.dispatch (action) to trigger the action to modify the state, write in the event handler, click the button to modify the state:

document.getElementById (' Red '). AddEventListener (' click ', Function () {
    Store.dispatch ({
        type: ' Red '
    })
})

document.getElementById (' green '). AddEventListener (' click ', Function () {
    Store.dispatch ({
        type: ' Green ')
    })
})

document.getElementById (' Toggle '). AddEventListener (' click ', Function () {
    Store.dispatch ({
        type: ') TOGGLE '
    })
})
Summary

All of the state in the application is stored in a single store in the form of an object tree, and the only way to change state is to trigger a action,action to describe what happened, Write reducer to change the state of the application according to the action.

First of all understand this point further study redux and redux with react use is not easier.

Welcome to my Homepage

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.