Use of React redux (compact version)

Before learning Redux, you should understand what is redux. Because the most popular way of learning is to understand what functions it can bring to your project and what problems it can solve before learning a certain knowledge!

start

redux is a JS library dedicated to state management, which centrally manages the state shared by multiple components in react applications.

It is not the work of the Facebook team, so it has nothing to do with React in essence. redux can also be used in Vue and Angular, but developers usually use it in combination with React. Vue also has its own state management library, Vuex.

First, to use redux, you must install this library:
npm i redux

redux has three core concepts:

  1. action
    1. Action object
    2. Contains two properties
      ·type: identifies the attribute. The value is a string. It is unique and necessary
      ·Data: data attribute. The value is of any type. Optional attribute
      Example: {type: "increment", data:{name: 'tom', age:18}}
  2. reducer
    1. Used for initialization status and processing status
    2. During processing, the pure function of new state is generated according to the old state and action
  3. store
    1. Objects that connect state, action and reducer
    2. How to get this object?
    1. import {createStore} from 'redux'
    2. import reducer from './reducers'
    3. const store = createStore(reducer)
    3. Function of this object?
    1. Get status value: getState()
    2. dispath(action): distribute the action, trigger the reducer call, and generate a new state
    3. subscribe(listener): register to listen. When a new state is generated, it will be called automatically

After understanding the basic concepts, let's make a small case

First of all, you need to create a redux directory under your project src to store the store JS file and reducer JS file.

store.js

/**
 * This file is specially used to expose a store object. The whole application has only one store object
 */

//It is specially used to create the most core store object in redux
import { createStore } from 'redux'
//Introduce reducer serving components
import reducer from './reducer'

export default createStore(reducer)

reducer.js

/**
 * This file is applicable to creating a reducer that serves components. The essence of reducer is a function
 * Note: multiple components have multiple reducers, and reducers are dedicated to their respective components
 *
 * reducer The function receives two parameters: the previous state and the action object
 */
//initialize value
const initState = 1;
export default function reducer(preState = initState,action){
    //Receive the type and data of the action object. This method is deconstruction assignment
   const { type,data } = action

    //Judge different types and carry out different operations
   switch (type) {
       case "increment":
           return preState + data
       case "decrement":
           return preState - data
       default:
           return preState;
   }
}

Let's define the store JS and reducer JS file, come to our component:
Import a custom store

import React, {Component} from 'react';

import store from '../../redux/store'
class Header extends Component {

    increment = (data)=>{
        store.dispatch({
            type:"increment",
            data
        })
    }

     componentDidMount() {
         //Detect the change of state in redux, and call render whenever the change occurs
         store.subscribe(()=>{
             this.setState({})
         })
     }

    render() {
        return (
            <div>
                <h2>The current summation is:{store.getState()}</h2>
                <button onClick={()=>this.increment(5)}>+1</button>
            </div>
        );
    }
}

export default Header;

In the above code, through store Getstate () can get the state value stored in redux. Since we only store a value, we directly return a value when getting it.
We distribute events through the dispatch API to change the value in the redux state. Then, when we initialize the component, we subscribe to the state of the store. If there is any change, we set the state of the component, and the component will call render again. Then we compare the virtual DOM and re render the changed value to the interface.

The update data in the above article is written in componentDidMount(). Of course, you can also write it in the index. Of your project root directory JS, for example:
index.js

import store from './redux/store'
ReactDOM.render(
       <App />,
    document.getElementById('root')
);
store.subscribe(()=>{
    ReactDOM.render(
           <App />,
        document.getElementById('root')
    );
})

This way of writing is to listen to the store state value globally. Once it changes, re render the APP. You don't need to worry about the rendering efficiency. The bottom layer of React will compare the new virtual DOM with the old virtual DOM through the diffing algorithm, which will only re render the virtual DOM that changes the data to the interface to generate the real dom, And its unchanged virtual DOM still uses the old one.

Keywords: React

Added by subalan on Sun, 30 Jan 2022 15:14:55 +0200