Preface:

There are often complex data flows in engineering projects. It is a problem that front-end engineers must solve to manage these data flows scientifically and efficiently. In the code, data flow management makes it easier to communicate between components and also makes the data easier to maintain. A common way to do this is to use redux. React can also be used to simplify operations. This article introduces Redux and react-redux. By the end of this article, you should have a relatively complete understanding of Redux and React-Redux and be able to use them in your projects.

A story,

  1. What is a redux?

Redux is a container for the predictable state of JS applications, according to the website. Is actually a global data state management tool (state manager), management data flow used to do component communication, etc. Note that there is no relationship between Redux and React. Redux supports React, Angular, Ember, jQuery, and even pure JavaScript

When redux is not used, passing values between sibling components is cumbersome and the code is complex and redundant. Using Redux to define a global single data Store, you can customize what data is stored in the Store, and the entire data structure is also clear.

  1. How does Redux manage data flow?

The figure above shows that Redux has a fixed process for data flow management. To understand this process, we first need to clarify three concepts: Store, Action and reducers.

  • Store: A store is a place where data states are stored. You can think of it as a data source for unified management of data. There can only be one store in the entire application, and all components can interact with the data in the Store through the Redux specification
  • Action: An action is a normal JavaScript object. The action must contain a type field of type string to indicate the action to be performed.
  • Reducers: Actions are sent to the store to change the state in the corresponding store based on the type in the action, but how? It’s through reducers, which is a pure function, and remember that Actions just describe the fact that something happened, not how the app updates the state, but rather reducers that change the data in the store based on the information in the Action object, right

Understand the Redux flowchart above these three nouns: When the component needs to change the data in store, it will send an action to Store. After receiving the action, Store will call the corresponding reducers function, which will return a new object to store as a new data value. The component then retrieves the updated data from the Store.

  1. With React, the code explains the use of redux

So how to define action, such as and define store, how to send action to store, how to update the data value in store, how to obtain the value in the new store in component? Let’s do it one by one.

First, we need to define action, reducers and Store respectively:

    / / respectively with three file actions. Js, reducers, js, store. Js to define the action, reducer, store
    
    As mentioned earlier, an action is a normal object that must have a type field
    const action={
      type:'ADD_TODO'.payload:'redux principle'
    }
    export default action;
    
    //reducers.js defines a pure function for handling state within a store
    const reducer =(state={},action) = >{
      switch(action.type){
        case ADD_TODO:
            return newstate;
        default return state
      }
      export default reducer;
      
   //store. Js Store is where data is stored for the entire project, and there can only be one. Create a store and reducer it
   import { createStore} from "redux";
   // Add the defined reducer
   import reducer from "./reducer.js";
   // Manage a store globally
    const store = createStore(reducer)
    export default store;

   // Now that the three files are defined, how does the component update the state in the store?
   //component.js, which defines one of our components
 
    import React, { Component } from 'react';  
    import store from './store';
    import action from './action';
    export default class Home extends Component {
        componentDidMount(){
            // Redux calls store. Subscribe to listen for store changes. Store.
            Subscribe unsubscribe is called when the page is unloaded. The purpose is to unsubscribe the page from listening on the store and prevent memory leaks
            let unsubscribe = store.subscribe(() = >
                  console.log(store.getState())
            );
            //unsubscribe();
        }
        change=() = >{
            // Store. dispatch will send the action to store, and store will automatically call reducers after receiving the action.
            // Reducers performs the corresponding processing logic according to the type in the action and returns the new state to the store,
            // Store. Subscribe () is triggered, and store. GetState () is used to fetch the state value in the store
            store.dispatch(action);
            // This is the code
           // store.dispatch({
            // type: 'ADD_TODO',
             // Payload: 'Redux'
            / /});
        }
        render() {
            return <div className='container'>
                <p onClick={this.change}>test</p>
            </div>}}Copy the code

This is a small example of how redux is used, including how the component sends an action to modify the store and how to get data from the store. This example should give you an idea of how to use Redux to manage data in your component code.

  • Defining actions, reducers, and stores is the foundation
  • Store is introduced into the component and automatically listens for changes within the store with store.subscribe()
  • If store needs to be changed in group price, use Store. dispatch(Action), and the reducers will automatically perform the corresponding logic to modify store after executing the reducers
  • To get a store from a component, use store.getState()

Second, the react – story

  1. What is React-redux?

React – Redux is a react plugin library designed to simplify the use of Redux in React applications. It is packaged from Redux, so the basic principles are the same as Redux, with some differences.

  1. The react – redux model diagram

React-redux divides all components into two broad categories: UI components (Presentational Components) and Container Components (Container Components)

UI components

  • Only responsible for the presentation of the UI, with no business logic
  • No state (that is, the this.state variable is not used)
  • All data is provided by the parameter (this.props)
  • Do not use any of Redux’s apis

Container components

  • Responsible for managing data and business logic, not UI rendering
  • With internal state
  • Use Redux’s API
  • The UI component is responsible for rendering the UI, and the container component is responsible for managing the data and logic

React-redux specifies that all UI components are provided by the user, while container components are automatically generated by React-Redux (generated by the connect() function). In other words, the user takes care of the visual layer, leaving state management to it

  1. How is React-Redux simplified compared to Redux?

As we already know, components interacting with stores using Redux need to import stores and manually call store.subscript() to listen for store changes, which is cumbersome to use. React-redux simplifies these steps and makes data flow management easier to use. These functions are supported by four React-Redux apis: Provider, Connect, mapStateToprops, and mapDispatchToProps

  • Component: React-Redux provides the Provider component, which contains the root component, and the Provider component needs to be passed into the Store so that all components can get state data
    // After the APP component is wrapped, all child components can get state data
    <Provider store={store}>
       <App />
    </Provider>
Copy the code
  • Connect: Provider passes to store, all child components get state. Connect is used to wrap UI components to generate container components. The connect wrap generates a container component, and the connect method takes two parameters: mapStateToProps and mapDispatchToProps. They define the business logic of the UI components. The former is responsible for the input logic, which maps state to the UI component’s parameters (props), and the latter is responsible for the output logic, which maps the user’s actions on the UI component to Actio, at which point you can interact with the Store.
import { connect } from 'react-redux'
  connect(
    mapStateToprops,
    mapDispatchToProps
  )(OurComponent)
Copy the code
  • MapStateToProps (): a function that sets up a mapping between the (external) state object and the (UI component’s) props object, attaching the store state to the component’s props. The mapStateToProps should return an object in which each key-value pair is a mapping.
    const mapStateToProps = (state) = > {
      return {
        todos: "todo value"}}Copy the code
  • mapDispatchToProps(): MapDispatchToProps is the second parameter to the connect function, which maps UI component parameters to the Store. dispatch method. It defines which user actions should be passed to the Store as actions. It can be a function or an object.
// Dispatch is store.dispatch, and ownProps is the props object of a container component
const mapDispatchToProps = (dispatch, ownProps) = > {
  return {
    onClick: () = > {
      dispatch({
        type: 'SET_VISIBILITY_FILTER'.filter: ownProps.filter }); }}; }Copy the code

Therefore, React-Redux uses the Provider component to manage stores in a unified manner, and uses the Connect package component to generate container components to connect data flows between stores and components. In this way, stores are not required to be introduced into each component, and store changes are monitored, which is more convenient to use