React-Redux and parse xreact-redux

Source: Internet
Author: User

React-Redux and parse xreact-redux

I have been exploring React-related things before. I have a SPA project on hand, so I am going to try the water on Redux. Redux is not associated with React itself. It is a common Javscript App module used for App State management. To use Redux in React projects, the better way is to use the react-redux library for connection. here it means that there is no react-redux, the two libraries will not be used together, but react-redux provides some encapsulation and a more scientific code organization method, this makes it easier for us to use Redux in React code.

Previously, we only used the Redux document to learn about react-redux. After some time of practice, we were prepared to repeat the source code and make some summary. The npm version of the code I see is v4.0.0, that is, the React version used is 0.14.x.

React-redux provides two key modules: Provider and connect.

Provider

The Provider module is used as the Container of the entire App. It is encapsulated on the basis of your original App Container. Its work is very simple. It accepts the Redux store as props, and declare it as one of the attributes of context. After declaring contextTypes, the child component can easily use this. context. store. However, we usually do not need to do this for our components. store in the context is used for the following connect.

This is an example of Provider usage:

// config app rootconst history = createHistory()const root = ( <Provider store={store} key="provider">  <Router history={history} routes={routes} /> </Provider>)// renderReactDOM.render( root, document.getElementById('root'))

Connect

This module is actually connected to Redux and React, and its name is also called connect.

First, consider how Redux operates: first, a state is maintained in the store, we dispatch an action, and then the CER updates the state according to this action.

Ing to our React application, the state maintained in store is our app state, and a React component acts as the View layer to do two things: render and response to user operations. Therefore, connect transmits necessary data in the store as props to the React component to render, and packs action creator to dispatch an action in response to user operations.

Okay. Let's take a closer look at what the connect module has done. First, its API is as follows:

connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options])

MapStateToProps is a function. The returned value indicates the state that requires merge to enter props. The default value is () => ({}), that is, nothing is passed.

(State, props) => ({}) // The second parameter is usually omitted

MapDispatchToProps can be a function. The returned value indicates that merge only needs the actionCreators of props. Here, the actionCreator should have been packaged with dispatch. We recommend that you use the bindActionCreators function of redux.

(Dispatch, props) => ({// The second parameter... bindActionCreators ({... ResourceActions}, dispatch)} is usually omitted )})

It is more convenient to directly accept an object. In this case, the connect function converts it into a function, which is exactly the same as the above example.

MergeProps is used to customize the merge process. The following is the default process. The parentProps value is the props of the component itself. It can be found that if the props of the component appears with the same name, it will be overwritten.

(stateProps, dispatchProps, parentProps) => ({ ...parentProps, ...stateProps, ...dispatchProps})

Options has two switches: pure indicates whether optimization is enabled. The default value is true. withRef is used to assign a ref to the component encapsulated in it, you can use the getWrappedInstance method to obtain this ref. The default value is false.

Connect returns a function that accepts the constructor of a React component as the connection object and returns the constructor of the connected component.

Then there are several questions:

  1. How does the React component respond to changes in the store?
  2. Why does connect select merge props instead of passing the entire state directly?
  3. What is pure optimized?

The function returned by connect is called Connector, which returns an internal component called Connect. On the basis of packaging the original component, it also monitors the changes in the Redux store internally, to allow the encapsulated components to respond to changes in the store:

trySubscribe() { if (shouldSubscribe && !this.unsubscribe) {  this.unsubscribe = this.store.subscribe(::this.handleChange)  this.handleChange() }}handleChange () { this.setState({  storeState: this.store.getState() })}

However, we connect a Container component, which does not hold all App states. However, our handler responds to all state changes, so we need to optimize the following: when the storeState changes, we only re-render the corresponding React component when we actually depend on that part of the state change. So what is the part that we actually depend on? It is obtained through mapStateToProps and mapDispatchToProps.

The specific optimization method is to check in shouldComponentUpdate. shouldComponentUpdate returns true only when the props of the Component Changes, mapStateToProps changes, or mapDispatchToProps changes, the check method is to compare shallowEqual.

So for a certain CER:

Export default (state ={}, action) =>{ return {... state} // The returned object is a new object, which may cause the component reRender // return state // It may not make the component reRender}

In addition, when connecting, be careful to map the state or actionCreators actually needed to props to avoid unnecessary performance loss.

Finally, based on the connect API, we found that ES7 decorator Can be used in combination with React ES6:

@connect( state => ({  user: state.user,  resource: state.resource }), dispatch => ({  ...bindActionCreators({   loadResource: ResourceActions.load  }, dispatch) }))export default class Main extends Component {}

OK. The above is all the content in this article. I hope it will be helpful for your learning and support for the customer's house.

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.