React-redux principle

Source: Internet
Author: User


React-redux principle analysis written in front


Previously wrote an analysis of the Redux in the store implementation of the article (see: Redux Principle (a): Store implementation analysis), suddenly realized, in fact, react and Redux have no direct contact. Redux, as a generic module, is primarily used to handle changes to the state in the application, and the presentation layer is not necessarily react.
But when we want to combine the two better in React+redux projects, we can connect through React-redux.
Based on the use of React-redux, this paper analyzes its realization principle.


React-redux


React-redux is a lightweight package library with only two core methods:


    • Provider
    • Connect


Let's analyze the effect one by one


Provider


Full source please poke here
The functionality of the provider module is not complex and is divided into the following two points:


    • Wrapping a layer on the original application component, making the entire application a provider subassembly
    • Receive Redux store as props, passed to connect on descendant components via context object


Here's a look at the specific code:


Package the original application


The [31-34] Render method renders its child elements so that the entire application becomes a subcomponent of the provider.
1.this.props.childrenis the react built-inthis.propsobject that gets all the subcomponents of the current component
2Children. A top-level object defined internally for react that encapsulates a number of methods that facilitate the operation of subcomponents.Children.onlyused to get only one subcomponent, no or more than one will be an error. It is important to note that the immediate child of the provider component is a single enclosing element, and do not place multiple components in parallel.


Delivery Store


[26-29] provider when initializing, gets to the store object in props;
[22-24] The external store object is placed in the context object so that connect on the descendant component can directly access the store in the context object.
1context. You can enable descendant components to get data or methods from the parent component directly, without having to pass through props down one layer at a level. Thecontextobject is equivalent to a separate space, the parent componentgetChildContext()writes the value to the space, and the descendant component that defines thecontextTypesvalidation canthis.context.xxxread the value of the XXX field from the context object.


Summary


All in all, the provider module features a simple function that encapsulates the entire application from the outside and passes the store to the Connect module.
And the core function is in the Connect module.


Connect


As this module is named, the Connect module is really connected to the react and redux.
Now, we can recall how Redux works: first we need to register a globally unique store object to maintain the state of the entire application, and when we want to change state, we dispatch an action. Reducer updates the corresponding state according to action.
Let's consider what we did when we were using React-redux:


 
import React from "react" import ReactDOM from "react-dom" import { bindActionCreators } from "redux" import {connect} from "react-redux" class xxxComponent extends React.Component{
    constructor(props){ super(props)
    }
    componentDidMount(){ this.props.aActions.xxx1();
    }
    render (
        <div>
            {this.props.$$aProps}
        </div>
    )
}

export default connect(
    state=>{ return {
            $$aProps:state.$$aProps,
            $$bProps:state.$$bProps, // ...
        }
    },
    dispatch=>{ return {
            aActions:bindActionCreators(AActions,dispatch),
            bActions:bindActionCreators(BActions,dispatch), // ...
        }
    }
)(xxxComponent)


With the above code, we can summarize the following information:



1. After using React-redux, the object we exported is no longer the originally defined Xxxcomponent, but the new React.component object that is wrapped by connect.
When connect executes, it returns a function (Wrapwithconnect), and its interior is bound to form a closure. After Wrapwithconnect execution, it is necessary to return a Reactcomponent object, in order to ensure that the original code logic can run normally, and this Reactcomponent object through the render of the original component, the package of the original component.
2. The render page requires the state fragment in the store tree, and changing the state requires dispatch an action, both of which arethis.propsobtained from. So when we call connect, the State and action passed in as a parameter are merged inside Connect and passed through the props to the reactcomponent of the package.
Well, the above is just our guess, see below for concrete implementation, full code please poke here.
The Connect full function declaration is as follows:


connect( mapStateToProps(state,ownProps)=>stateProps:Object, 
    mapDispatchToProps(dispatch, ownProps)=>dispatchProps:Object, 
    mergeProps(stateProps, dispatchProps, ownProps)=>props:Object,
    options:Object
)=>( component
)=>component


Then look at the Connect function body structure, we take the core steps to describe


export default function connect (mapStateToProps, mapDispatchToProps, mergeProps, options = ()) {
     // parameter processing
     // ...
     return function wrapWithConnect (WrappedComponent) {
        
         class Connect extends Component {
             constructor (props, context) {
                 super (props, context)
                 this.store = props.store || context.store;
                 const storeState = this.store.getState ()
                 this.state = {storeState}
             }
             // Periodic method and operation method
             // ...
             render () {
                 this.renderedElement = createElement (WrappedComponent,
                     this.mergedProps // mearge stateProps, dispatchProps, props
                 )
                 return this.renderedElement;
             }
         }
         return hoistStatics (Connect, WrappedComponent);
     }
} 


In fact, has basically confirmed our speculation:
1, connect through the context to obtain provider in the store, through Store.getstate () to get all the state on the store tree.
2. The return value of the Connect module is wrapwithconnect as function.
3, Wrapwithconnect returns a Reactcomponent object Connect,connect re-render the external incoming component wrappedcomponent, The mapstatetoprops passed in Connect, Mapdispatchtoprops and the original props on the component are merged and passed to Wrappedcomponent through the property.



Let's analyze the meaning of each function in conjunction with the code.


Mapstatetoprops


mapStateToProps(state,props)Must be a function.
The parameter state is all state in the store tree, and the parameter props is the incoming props through the component connect.
The return value represents the state that needs to merge into the props.



The above code is used to calculate the state,[104-105 to merge] to get the merge state by callingfinalMapStateToProps. Where the state is obtained as a parameterstore.getState(), it is obvious that all the state in the store tree


Mapdispatchtoprops


mapDispatchToProps(dispatch, props)Can be a function, or it can be an object.
The parameter dispatch is astore.dispatch()function, and the parameter is props to the props passed through the component connect.
The return value represents an action that requires the merge into props.



The code above is used to calculate the action to merge, and the code logic is very similar to the computed state. As a parameter,dispatchYesstore.dispatch.


Mergeprops


mergePropsis a function, definedmapState,mapDispatchandthis.propsthe merge rule, the default merge rule is as follows:



It is important to note that if a field in three objects has the same name, the former will be overwritten by the latter



If the method is registered via connect, themergePropsabove code will bemergePropsmerged using the defined rules, andmergePropsthe merged result will pass through the props to the Connect component.


Options


optionsis an object that containspureandwithReftwo properties


Pure


Indicates whether pure optimization is turned on, and the default value is True


Withref


The withref is used to give a ref to the component that is wrapped inside, which can be obtained by the Getwrappedinstance method, which defaults to false.


How react responds to store changes


At the beginning of the article we also mentioned that react is not directly related to redux, that is to say, redux dispatch trigger the state change in the store tree, and will not cause react to re-render.
React-redux is the module that really triggers react re-rendering, so how does this process happen?
Just mentioned, the Connect module returns a Wrapwithconnect function, and a connect component is returned in the Wrapwithconnect function. The Connect component features the following two points:
1, packaging the original components, the State and action through the props of the way into the original components inside
2, monitor the store tree changes, so that its packaging of the original components can respond to state changes
Below we mainly analyze the 2nd:


How to register for monitoring


Redux, you canstore.subscribe(listener)register a listener. Listener will be executed after the store tree is updated.



The above code is the process of registering listener with the store tree inside the Connect component.
[199] The callstore.subscriberegisters ahandleChangelistener named, and the return value is the logoff function of the current listener.


When to register





As you can see, when the Connect component is loaded into the page, the current component starts listening for the store tree change.


When to log off


When the current connect component is destroyed, we want the registered listener to be destroyed as well, to avoid performance issues. You can nowcomponentWillUnmountperform this procedure in the cycle function of Connect.


Change processing logic


With the timing of triggering a component update, we'll look at how the component triggers a re-render



The [244-245] connect component, when initialized, alreadythis.statecaches state in the store tree in. These two lines compare the current state status and the state before the change, respectively.
[262] The comparison process is temporarily skipped, and this line will eventually update the state in the store tree to the statethis.setState()within Connect, and thethis.setState()method can trigger the re-rendering of Connect and its subcomponents.


Summary


As you can see, the core functionality of React-redux is in the Connect module, and understanding this module will help us better use React-redux to handle business problems and optimize code performance.


Summarize


This article through the analysis React-redux source code, introduced the provider and the Connect module in detail, has combed the reat, the Redux, the React-redux three relations.
Personally feel that more to see the source code is also very good, on the one hand can deepen their understanding of the use of the framework, on the other hand can learn some excellent programming ideas.
Technology this path, understand more, do not understand the more, learning, rashness.


Category: React


React-redux principle


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.