Redux and React-redux use of the detailed

Source: Internet
Author: User
Tags list of attributes

My own understanding redux is similar to the Vuex in Vue, is a data manager, say, we start from the classic counter case to explain

Implementing counters using Redux

Create the following react project, I used to put each module block, only so many files, of course you can also write in a JS file, this is not the focus

First, let's look at the entry file for the project Index.js

Import ' Core-js/fn/object/assign '; import React from' React '; import Reactdom from' React-dom '; import Counter from'./components/counter ';//Introduction of counting DevicesImport {CreateStore} from ' Redux ';//get ready for the creation of the store by deconstructing it to CreateStoreImport reducer from './reducers/index '//introduce the Reducer pure function, which, depending on the type of action, combines the old state to return the newLet store = CreateStore (reducer);//Create Redux's core store store I'll get back to you with detailed answers.Import {Numadd,numdel} from './actions/index ';//introduce the action function to trigger what action, depending on how the operation changes the value//Render The main component into the DOM//The redducer variable is used here to define the render function in the Reactdom, which is convenient for the page rendering after the state update in the storeConst Redducer = () ={Reactdom.render (<Counter Value={store.getstate ()} Add={() =Store.dispatch (Numadd ())} del={() =Store.dispatch (Numdel ())}></counter&gt, document.getElementById (' app ')  );};//value={store.getstate ()} to the presentation component counter Pass the data here the value of Store.getstate () is the initial state value inside the reducer pure function during store creation//() =>store.dispatch (Numadd ()) and () =>store.dispatch (Numdel ()) Define functions passed to the presentation component counter//store.dispatch (parameter) passes an object as a parameter such as {type: "Add"}, calls the Reducer pure function, implements the update of state in storeredducer ();//when the function executes, it initializes the pageStore.subscribe (redducer);//Store.subscribe () is used to listen for changes in the big state of the store and to re-render the page if a change occurs, so it binds to Redducer () .

In the view of pure function reducer, as to why Redux is responsible for state editing functions collectively referred to as reducer, my own guess is based on the reduce method in es5 (purely blind speculation, do not take seriously)

Const REDUCER = (state=0,action) = ={  Switch(action.type) { Case' Add ':      returnState+1;  Case' Del ':      returnState-1; default:      returnState }};//defines the store's state = 0,action accepts a value that is an object of Store.dispatch (Numadd ()) through the Numadd () function//Since this function is bound to the CreateStore in Redux in the previous store, this code let store = CreateStore (reducer)//so you can change the store's state value here, so now you can understand why reducer is a pure function.ExportdefaultReducer

Look at the export function in the actions

Export Const NUMADD = () ={  return{    type:' Add '  = () = () ={   return {    type:' del '  }}// export two functions, each returning an object containing the type attribute (note that the type in ation is required, Other properties can be added by themselves, and can be refactored to assign a function that is worth every /// , like this code in the portal file Index.js import {Numadd,numdel} from './actions /index ';

Finally see the display component counter

Import React from ' React ';//The function returns the component, which is to deconstruct the assigned value to get the data//Const Counter = ({value, add, del}) =>{//Return (//<div>//<p style={{color: ' Red '}}>//number of clicks {Value}//</p>//<button onclick={add}> plus a </button>//<button onclick={del}> minus one </button>//</div>//   )// };//class returns a component by directly acquiring the properties of the current component itself, you can get the data you want.class Counter extends React.component {render () {return (      <div> <p style={{color: ' Red '}}>Click Times { This. Props.value}</p> <button onclick={ This.props.add}> plus a </button> <button onclick={ This.props.del}> minus one </button> </div>)}}exportdefaultCounter;

Here I used two ways to create the component, the first component created through a function, to get the data passed in the portal file Index.js, can only be used to deconstruct the assignment to the data through the parameter, the second kind of component created through class can only get the data through the component's own properties, Of course, you can also get the data you want by deconstructing the assigned value, the code is as follows

class Counter extends React.component {  render () {    this. props;     return (      <div>        <p style={{color: ' Red '}}>           clicks {Value}        </p>        <button onclick={add}> plus one </button>        <button onclick={del}> minus one </button>      < /div>    )  }

All of the code to achieve a simple counter function, this is the most basic use of Redux, Tip: Redux and reat-redux need to install themselves, it is best to use--save to install

The next step is to use Redux and React-redux to implement the counter

And look at the code

Import React, {Component} from ' React '//introduction of ReactImport proptypes from ' Prop-types '//introduce throttling UI component (presentation component) Property RestrictionsImport reactdom from ' React-dom '//introduction of React-dom related objectsImport {CreateStore} from ' Redux '//Introduction of ReduxImport {Provider, connect} from ' React-redux '//introduction of react supporting Redux//Create a React component (or virtual node)class Counter extends Component {render () {const {value, Onincreaseclick}= This. Props; //the value of the corresponding attribute is obtained by the deconstruction assignment.    //here counter is the UI component (presentation component) whose property is the state in the container component outside it is passed through the Connect operation in React-redux    return (      <div> <span>{value}</span> <button onclick={onincreaseclick}>increase</button> {/*by clicking on the event to trigger the binding property, it is clear that here Onincreaseclick is a method or a key value of an object whose mapped value is a function*/}      </div>    )  }}//limit the list of attributes in the presentation component to the individual merit type.Counter.proptypes ={value:PropTypes.number.isRequired,//the value in the Property object must be of type number and must have a valueOnIncreaseClick:PropTypes.func.isRequired//the Onincreaseclick in the Property object must be a function and must have a value};//The definition here is an action object, my understanding is similar to the action in Vuex, send different action names, through the matching other functions of the listener//The State of the container component is changed, except that the actions in Vuex are the Send action name, and the redux is different depending on the value of the type in the Actions object.Const Increaseaction= {type: ' Increase ' };//define the Reducer pure function, the function of reducer is, according to the action and the state value//then, depending on the value of the type of the action, the new state is returned to the UI component (presentation component) for re-renderingfunctionCounter (state = {count:0}, Action) {const Count=State.count; Switch(action.type) { Case' Increase ':      return{Count:count + 1 }; default:      returnState }}//To create a store object, it can be said that store is the core of redux, because according to Redux's design concept,//operations on state are implemented according to various methods in the store and are easy to manage//Here we use the Redux CreateStore and reducer pure functions to get the store we want.Const STORE =createstore (counter);//Mapstatetoprops is the first parameter of connect//According to the name we know is to map the state in the previous reducer pure function and the props (property) of the presentation componentfunctionMapstatetoprops (state) {return{Value:state.count}}//Mapdispatchtoprops is the second parameter of connect//by name we can tell that the dispatch method in the reducer and the props (property) of the presentation component in the store before the pure function are mappedfunctionMapdispatchtoprops (Dispatch) {return{onincreaseclick: ()=Dispatch (Increaseaction)}}//this defines the app as a container component in the React-redux design concept//the corresponding container component app is derived by combining the pass-through parameters and the presentation component counter in Connect//the container component app here contains the display components counterConst APP =Connect (Mapstatetoprops, Mapdispatchtoprops) (Counter);//render container component app to target element//the component provider here is a special component in a React-redux//Note: 1. There is only one sub-component in provider (this is the app container component, not necessarily the container component, which operates on its own business requirements)//2. The advantage of using the provider component is that you only need to set the properties for the provider component, so that its subcomponents and subcomponents in its subcomponents can use their corresponding properties directly//3. Avoid a complex operation that passes after a component is nestedReactdom.render (<provider store={store}> <app/> </provider>, document.getElementById (' App '))

Here to complete the combination of Redux and react-redux, through their own study, I found that the programming idea is how important, I sigh at the depth of React-redux this thought, the overall feeling clean, so that the display components and components are separated from each other and a certain combination, Part-time is entangled, but it does not violate the idea of component separation, is simply powerful

, the basis of the Redux and React-redux to the end of the explanation, I will also write Redux asynchronous programming understanding, after all, is now synchronous implementation

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.