As a React project becomes more hierarchical and has more pages, there will be more requirements for data transfer between component levels and pages, and many variables will need to be managed globally. At this point, the use of redux and React-Redux becomes necessary. They can help us easily manage the data of the whole project.

Below, I would like to write down my own experience of learning and using Redux and React-Redux, as a record and share of the learning process.

Redux and React-Redux

1.1 the action

An Action is a payload that transfers data from the application (not called a View here because it could be a server response, user input, or other non-View data) to the Store. It is the only source of store data. Typically, you will pass the action to the store via store.dispatch().

1.2 reducer

Reducers specifies how changes in application state can be sent to the Store in response to actions. Remember that Actions only describe the fact that something happened, not how the application updates state.

1.3 store

Store is an object that links actions and reducer together. In essence, store is a state tree that saves the state of all objects. Any UI component can access the state of a particular object directly from the Store.

In Redux, all data (such as state) is stored in a store container, and there can only be one Store object in an application. When a store receives an action, it will delegate the action to the relevant Reducer. Reducer is a pure function that looks at the previous state, performs an action and returns a new state.

1.4 the Provider

A Provider is simply an outer container that interacts with Connect to transfer data across hierarchies. To use it, just define the Provider as the outermost component of the project and set up the Store. Then the entire project can access the store directly. React uses [Context](). Its roughly core code is as follows:

import React, {Component} from 'react'
import {PropTypes} from 'prop-types'

export default class Provider extends Component {
    getChildContext() {
 return {store: this.props.store}  }   constructor() {  super(a)  this.state = {}  }   render() {  return this.props.children  } }  Provider.childContextTypes = {  store: PropTypes.object } Copy the code

1.5 the connect

Connect connects the React component to the Redux Store. It is wrapped one layer outside of our container component. It receives state and Dispatch from the store provided by the Provider above, passes it to a constructor, and returns an object. To our container component as a property.

It has four parameters mapStateToProps, mapDispatchToProps, mergeProps, and options.

The mapStateToProps function is to bind the state (data source) of a store to the props of a specific component The other two methods are not generally used, so I will not introduce them here.

How does Connect connect the React component to the Redux Store? The main logic can be summarized in the following code:

import {Component} from "react";
import React from "react";
import {PropTypes} from 'prop-types'

const connect = (mapStateToProps, mapDispatchToProps) = > (WrappedComponent= > {
 class Connect extends Component {  constructor() {  super(a)  this.state = {}   }   componentWillMount() {  this.unSubscribe = this.context.store.subscribe((a)= > {  this.setState(mapStateToProps(this.context.store.getState()))  })  }   componentWillUnmount() {  this.unSubscribe()  }   render() {  return <WrappedComponent {. this.state}  {. mapDispatchToProps(this.context.store.dispatch)} / >  }  }   Connect.contextTypes = {  store: PropTypes.object  }  return Connect })  export default connect Copy the code

Use of redux and React-redux

The folder directories for Redux in the project are as follows


Take the need to manage user information data

The first step is to write an action that operates on user information

import {USER_INFO} from ".. /constants/actionTypes";
import store from '.. /store/store'

export const switchUser = (data) = > {
    console.log("switchUser()",data);
 return (a)= > {  store.dispatch({  type: USER_INFO, . data })  } } Copy the code

The second step is to compile a reducer that changes the user information and return the new state

import {USER_INFO} from ".. /constants/actionTypes";

const redUserInfo = (state = {
    userId: 10001.    userName: ' '. userOpenid: ' '. userPhone: ' '. userRole: 0 }, action) => {  if (action === undefined) {  return state  }   switch (action.type) {  case USER_INFO:  return { . state,. action }  default:  return state  }  } Copy the code

Step 3, complete the creation of the Store

import {createStore} from 'redux'
import reducers from '.. /reducers/index'

let store = createStore(reducers)

export default store Copy the code

The fourth step is to obtain user information

// Configure the code to connect the component to the store via connect
let mapStateToProps = (state) = > ({
    userInfo: {... state.redUserInfo}})

let mapDispatchToProps = (dispatch) = > ({})  export default connect(mapStateToProps, mapDispatchToProps)(PageClass)  // Get user information from props this.props.userInfo Copy the code

Step 5: Modify user information

import {switchUser} from '.. /.. /redux/actions/userInfo'

switchUser({
    userId: 10001.    userName: ' '. userOpenid: ' '. userPhone: ' '. userRole: 2 }) ();Copy the code

This completes a simple process for using redux+React-redux