Use redux to manage your react apps

Source: Internet
Author: User
Tags javascript array

React is the best front-end library because it originates from the best backend language framework in the world. ---beliefs

4.0 'll likely is the last major release. Use Redux instead. It ' s really great. -flummox Framework author Acdliteandrew Clark

Why use react also need to use other framework to match?

The core of react is the performance of the component-defined interface, which is a front-end library of the view layer, and we usually need a set of mechanisms to manage the communication between the component and the component and the data model when using react.

Why use redux?

Facebook officials have proposed a flow of flux thought management data, while also giving their own implementation to manage react applications. But when I opened the flux document, the tedious implementation, and the long, smelly document, it was hard for me to have the desire to use it. Fortunately, the community and I have a similar idea of a few, GitHub also emerged on the implementation of the framework of flux, more famous Redux,reflux,flummox.

One of the redux's simple and interesting programming experiences is the place that attracts me the most.

    • Simple. Unlike other flux implementations, Redux has only a single state tree, and I just need to manage a state tree no matter how complex the project is. Maybe you have questions, a state tree is enough? How big is this state tree? Don't worry, the reducer mechanism in Redux can solve this problem.

    • Interesting. When you are busy iterating over projects, how long have you been experiencing the fun of programming? Look at this picture below, what is the Debug tool on the right? is the action and state of the entire application so easily managed? Behavior can also be saved, deleted, rolled back, reset? Changed the code, the page does not refresh can also produce changes? Don't joke, no, the world is so big, let me try!

Note: Redux Development debugging Tool: Redux-devtools
React app No refresh Save tool: Hot-loader

Unknown to the masses of the truth, may need me here Lai an the idea of flux data flow, look at the graph:
  ╔═════════╗       ╔════════╗       ╔═════════════════╗  ║ Actions ║──────>║ Stores ║──────>║ View Components ║  ╚═════════╝       ╚════════╝       ╚═════════════════╝       ^                                      │       └──────────────────────────────────────┘  注意:图片仅仅是FLUX思想,而不是Facebook的实现。

The general process is that the view layer cannot operate directly on the state, but relies on the actions dispatch instructions to tell the store to modify the status, the store receives the actions instructions, the corresponding changes, the view layer along with the store changes.

For example, a component should change the B component. First, the a component needs to execute an action that tells the store of the binding B component to change, and the store receives the order after it has been dispatched, and the corresponding B-component view changes. If the C,d,e,f component is bound to the same store as the B component, then c,d,e,f will change as well.

Develop a small program using react and redux

To better describe how to use redux to manage react applications, I did a small example of manage items. You can find all the source code here: Https://github.com/matthew-sun/redux-example.

Quick View
1.git Clone [email protected]:matthew-sun/redux-example.git2.npm install && npm start3.open localhost:3000
Directory structure
. +--app|   +--actions|       +--index.js|   +--components|       +--content.js|       +--footer.js|       +--searchbar.js|   +--constants|       +--actiontypes.js|   +--containers|       +--app.js|   +--reducers|       +--index.js|       +--items.js|       +--filter.js|   +--utils|   +--configurestore.js|   +--index.js+--css|   +--pure.min.css+--index.html
Index.js

In the portal file, we need to connect the app with the redux. Provider is a component provided by React-redux that binds the store and view together, where the store is the only state tree. When the store changes, the entire app can make a change. {() \ =} is a props.children that declares a returned function to be passed into the provider, and this method will be simplified in the 0.14 version of react.

/* app/index.js */import React from ' React ', import {Provider} from ' React-redux ', import app from './containers/app '; impo RT Configurestore from './configurestore '; Const store = Configurestore (); React.render (    <div>        <provider store={store}>            {() = <app/>}        </provider >    </div>,    document.getElementById (' app '));
Constants

Keymirror This method is very useful, it helps us to easily create constants that are equal to key-value keys.

/* app/constants/actiontypes.js */import keymirror from ' react/lib/keymirror '; export default Keymirror ({    Add_item : null,    delete_item:null,    delete_all:null,    filter_item:null});//equals//Export Const Add_item = ' Add_item ' ;//Export Const Delete_item = ' delete_item ';//export Const Delete_all = ' delete_all ';//export Const Filter_item = ' FILT Er_item ';
Actions

Action to distribute instructions to the store, the action function returns a Javascript with the type attribute Plain Object,store will execute the corresponding method according to the different action.type. Asynchronous operation of the AddItem function I used a little bit of finesse, using the Redux-thunk middleware to change the Dispatch,dispatch is bound with bindactioncreators in the view layer. Using this changed dispatch we can send an asynchronous instruction to the store. For example, you can put a request to the server (AJAX) in the action, and it is strongly recommended to do so.

/* App/actions/index.js */import {add_item, Delete_item, Delete_all, Filter_item} from '. /constants/actiontypes '; Export function AddItem (item) {    return dispatch = {       SetTimeout () = Dispatch ({ Type:add_item}),    }}export function DeleteItem (item, E) {    return {       type:delete_item,       item    } }export function DeleteAll () {    return {       type:delete_all    }}export function Filteritem (e) {    let Filteritem = E.target.value;    return {       Type:filter_item,       filteritem    }}
Reducers

Redux there is only one state tree, in order to avoid the state tree becoming more and more complex, Redux is responsible for managing the entire application's states tree through reducers, and reducers can be divided into reducer.

Reduce appears in the JavaScript array method, but is less common. Simply and quickly use the code sample to review:

  /* Array.prototype.reduce */var arr = [1,2,3,4];var initialvalue = 5;var result = Arr.reduce (function (Previousvalue, Curre Ntvalue) {    return previousvalue + currentvalue}, InitialValue) console.log (Result)//15//The return value of the callback function is the cumulative result, And this return value is supplied as a parameter the next time the callback function is called. The process of performing the entire function is roughly the same ((((5+1) +2) +3) +4)

Returning to Redux, the whole state is equivalent to getting a new state from [the initial state]merge a [action.state], and the process of getting a new state with the constant introduction of the action. (previousstate, action) = newstate, note: Do not change the previousstate under any circumstances, because the view layer can only be compared with a simple comparison when comparing state changes, and avoids the deep cycle comparison. Reducer data structure We can use IMMUTABLE-JS, so that we can easily skip the update of the component subtree that the state does not change by simply react-immutable-render-mixin the plugin on the view layer.

/* app/reducers/items.js */import immutable from ' immutable '; import {add_item, Delete_item, Delete_all} from '. /constants/actiontypes '; Const INITIALITEMS = immutable.list ([+ +]); Export default function items (state = Initialitems, action) {    switch (action.type) {case        Add_item:            return State.push (state.size!=0? State.get ( -1) +1:1);        Case Delete_item:             return State.delete (State.indexof (Action.item));        Case Delete_all:            return State.clear ();        Default:            return state;    }}
Connection reducers

The Combinereducers function provided by Redux can help us to combine the reducer so that we can split the reducers into small reducer to manage the store.

/* app/reducers/index.js */import {combinereducers} from ' Redux ', import items from './items ', import Filter from './filte R '; Const Rootreducer = Combinereducers ({  items,  filter}); export default rootreducer;
Middleware

In redux, 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-Type action objects.

Take Redux-thunk as an example:

/* Redux-thunk *  /export default function Thunkmiddleware ({dispatch, getState}) {  return next =      action = >        typeof action = = = ' function '?          Action (Dispatch, GetState):          Next (action);}

When Thunkmiddleware determines that the action passed in is a function, the thunk function is given the dispatch and GetState parameters, otherwise, the next action is called, and the subsequent middleware (middleware Plug-ins can be bound multiple) to get the chance to use dispatch.

/* App/configurestore.js */import {compose, createstore, applymiddleware} from ' Redux '; import thunk from ' redux-thunk '; i Mport rootreducer from './reducers '; var buildstore = Compose (Applymiddleware (thunk), createstore) export default function Configurestore (initialstate) {   return Buildstore (Rootreducer, initialstate);}
Ui

Smart components and puppet components, because this article is mainly about redux, interested students can take a look at this article smart and DUMB component. In this project, the smart component is placed in the containers, and the puppet component is placed in the components.

Containers

Smart components convert State and actions to the props required by their puppet components through the Connect function provided by the React-redux function.

/* app/containers/app.js */import React from ' React ', import searchbar from '. /components/searchbar '; import Content from '. /components/content '; import Footer from '. /components/footer '; import {connect} from ' React-redux ', import immutablerendermixin from ' React-immutable-render-mixin '; import * as Itemsactions from '.     /actions '; import {bindactioncreators} from ' redux '; let App = React.createclass ({mixins: [immutablerendermixin],         Proptypes: {items:React.PropTypes.object, filter:React.PropTypes.string}, render () { Let styles = {width: ' 200px ', margin: ' 30px auto 0 '} const ACTIONS = This.props.         Actions Return (<div style={styles}> Components

The puppet component, with its own responsibilities, has nothing to do with the actions and stores, and it can be used independently in the project, and can even be tied to other actions,stores.

    • Searchbar: Find Item.
    • Content: Controls the display of items and deletes an item.
    • Footer: Add Item, delete all item.
Debugging Tools

With Redux-devtools debugging, you have fun in the development process.

/* App/index.js */function Renderdevtools (store) {if (__debug__) {let {DevTools, Debugpanel, logmonitor} = require ('    Redux-devtools/lib/react '); Return (<debugpanel top right bottom> <devtools store={store} monitor={logmonitor}/> </d  ebugpanel>);  }else {return null; }}react.render (<div> <provider store={store}> {() = <app/>} </prov ider> {Renderdevtools (store)} </div>, document.getElementById (' app ');/* App/configurestore.js */var B Uildstore;if (__debug__) {Buildstore = Compose (Applymiddleware (thunk), require (' Redux-devtools '). Devtools (), RE    Quire (' Redux-devtools '). Persiststate (Window.location.href.match (/[?&]debug_session= ([^&]+) \b/)), CreateStore)}else {buildstore = Compose (Applymiddleware (thunk), createstore)}export default function Configurestore (i Nitialstate) {return Buildstore (Rootreducer, initialstate);}

Add the two snippet of code in your code and run the NPM Run debug command to manage your project with the Debug tool.

Extended Reading
    • Redux Document
    • Awesome-redux
Written in the last

When I first came into contact with Redux and react technology, I almost had trouble sleeping every night, and the new ideas of technological innovation always stimulated my brain. It is highly recommended that you also try Redux and experience the happiness I get from development.

If there's anything you want to know, welcome to my GitHub and interact with me.

Use redux to manage your react apps

Related Article

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.