React loves you-Insight redux outfit's force

Source: Internet
Author: User

If you pretend to be forced, please take me to fly!

Once upon a time, I heard that react only responsible for the UI, saying that angular code is like writing back end, now it seems, react win in the feelings;

I think there is no need to always compare react and angular, angular is a relatively complete set of chatty framework, and react is really only responsible for the UI, just a lot of the concept of things, you need to construct React more like to build a react as the main line of the ecology, component-based, virtual DOM to solve performance bottlenecks, one-way data Flow Unified management Components,webpack, ES6, jsx perfect integration, and flux, Redux and other architectures and their surrounding expansion, plus react Native; Well, it's just the UI, it's all-in-one rhythm! This is a line of sentiment, hit many front-end people long-term web exploration pain point: Web Components, so to flap arm, should be gathered, and when you really start to walk into react, you will find, as Loro said: "Beautiful not like the strength!" ”;

It is a coincidence that before the blog has a "Rich text editor-about undo, redo operation," is about the simple canvas operation and Rich text editor custom undo Redo method, now found that the low burst, because there is a redux in the document about undo redo instance , is to be Redux taught a person, so formally decided to start Redux, say redux for generally not so complex there are many state management place is not necessary, originally states and props can play well, now halfway killed a redux, and full control of the state, so high force lattice, please take me to fly!

Don't ask what redux is ... The guy who's going to be in charge of all your components state! In Redux's readme, it is:

Redux is a JavaScript state container that provides predictable state management.

If you do not understand redux, then see this sentence, you may still very calm, or the brain began to spin, some indefinitely, even a little confused, alas, in fact, is still not understand it!

Since the state is a passer-by, then we have to start writing action and Reducer, together into the redux;

Redux provides a set of mechanisms, so it is not too easy to accept, say react from the beginning to now there are too many not easy to accept the place, the key is that there is a force lattice, so want to fly higher, it should forget the horizon! Redux is a JavaScript state container, also called store, which is a tree of objects made up of all the component States, or it can be seen as a large JSON, or a small database belonging to the front end, no longer operating state, but the large JSON for the additional pruning ; only the mode of operation is provided by Redux;

1. Action and Actioncreator

Action is the source of the store data, itself is a normal JS object, the Type field is necessary to indicate what to do; actions of different business types can be stored separately, and the Actioncreator function returns only one action, by dispatch ( Action) call to update state;

1 //Action Type:datas2Export Const add= ' ADD ';3Export Const del= ' DEL ';4 5 //Action Creator:datas6ExportfunctionAddOne (data) {7     return {8 Type:add,9 Payload:dataTen     } One } AExportfunctiondelone (INS) { -     return { - Type:del, the Index:ins -     } -}

As above, two action Type:add and Del are declared, two actioncreator:addone and DeLone, respectively, return an action;

2, Reducer

The action merely indicates what has been done, and Reducer indicates what to do;

1 //Reducer2Import {Add,del} from './actions ';3Const INITDATASSTATE={DATAS:[],LENGTH:0};4ExportfunctionDatasjson (state=initdatasstate,action) {5     Switch(action.type) {6          CaseADD:7         return{datas:[...state.datas,action.payload],length:state.length+1};8          CaseDEL:9         if(state.length<=0) {Ten             returnState ; One         } AState.datas.forEach ((a,i) ={ -I==action.index&&state.datas.splice (i,1); -         }); the         return{datas:state.datas,length:state.length-1}; -         default: -         returnState ; -     } +}

Reducer is a pure function that receives the old State and action, returning the new State; (previousstate,action) =>newstate;

Reducer can be split into multiple, and finally merged by Combinereducers;

1Import {combinereducers} from ' Redux ';2 //Reducer13 functionReducer1 (initstate,action) {4     //return newstate5 }6 functionReducer2 (initstate,action) {7     //return newstate8 }9ExportdefaultCombinereducers ({reducer1:reducer1,reducer2:reducer2});

3. Connecting Redux

After the introduction of Redux, your app.js may have to write:

1Import React from ' React ';2Import {Connect} from ' React-redux ';3Import {Addone,delone} from './actions ';4 5 class App extends react.component{6 render () {7         return (8<div>9<input type= "button" onclick={ This. Props.onadd} value= "Addoneitem"/><br/>Tenlength:<b>{ This.props.length}</b>;d atas:<i>{this.props.value}</i><br/> One<input type= "button" onclick={ This. Props.ondel} value= "Delfirst"/> A{ This. Props.children} -</div> -         ); the     } - } -  - functionMapstatetoprops (state) { +     return { - value:JSON.stringify (state.datas), + Length:state.length A     } at } - functionMapdispatchtoprops (Dispatch) { -     return { -Onadd: () ={ -Let Data={id:math.round (Math.random () *10), Text:Math.round (Math.random () *1000000000). toString (16)}; - Dispatch (AddOne (data)); in         }, -Ondel: () ={ toDispatch (DeLone (0)); +         } -     } the } *  $ExportdefaultConnect (Mapstatetoprops,mapdispatchtoprops) (APP);

Now the state has all been left to Redux Escrow: Mapstatetoprops maps the bind to Props;mapdispatchtoprops to a props,connect to connect that component with Redux Since the state is gathered in the store, the values and modifications of the mapped props will all point to the store, which is resolved by provider;

4, Provider

1Import React from ' React ';2Import reactdom from ' React-dom ';3Import {CreateStore} from ' Redux ';4Import {Provider} from ' React-redux ';5Import {reducers} from './reducers ';6Import App from './app ';7 8Const store=CreateStore (reducers);9 Console.log (Store.getstate ());Ten Reactdom.render ( One<provider store={store}> A<App> -&LT;INPT/> -</App> the</provider>, -document.getElementById (' views ')) -);

Now provider as the outermost container and bound to the value of store, so that the inside of the component map into the props state will be able to fetch values, so that the basic introduction of Redux, may be this simple additions and deletions datas of the thing, With angular and jquery are a few lines of code, but here to dozens of lines of code, and mixed with a bunch of concepts, and redux not just these, like middleware, higher-order functions and so on in the next exploration will again refresh your horizons; I just want to say, you don't heaven! But, this high force lattice, haha, please take me to fly!

If you are on the road, go ahead bravely!

The original is from: the blog of the Full House

React loves you-Insight redux outfit's force

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: 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.