Explanation of the working principle and usage of redux

Explanation of the working principle and usage of redux

1. What is redux?

React is just an abstraction layer for the DOM, not a complete solution for web applications. React is just a lightweight view layer framework. If you want to build a large application, you must use it with the view layer framework redux. It is mainly used in scenarios with multiple interactions and multiple data sources. It is not necessary to use it, but you must know how to use it.

2. The principle of redux

The principle of redux is first explained with a picture, which is easy to understand

First, the user issues an Action.

store.dispatch(action);

Then, the Store automatically calls the Reducer and passes in two parameters: the current State and the received Action. The Reducer returns the new State.

let nextState = todoApp(previousState, action);

Once the State changes, the Store will call the listening function.

//Set the listening function store.subscribe(listener);

The listener can get the current state through store.getState(). If you are using React, this can trigger a re-rendering of the View.

function listerner() {
  let newState = store.getState();
  component.setState(newState);   
}

3. How to use redux?

(1). Install redux, create a redux folder, and create store.js

This file is specifically used to expose a store object. The entire application has only one store object.

Install redux: yarn add redux / npm install redux

//Introduce createStore, which is specifically used to create the core store object in redux import {createStore, applyMiddleware} from 'redux'
//Introduce the reducer that serves the Count component
import countReducer from './count_reducer'
//Introduce redux-thunk to support asynchronous actions
import thunk from 'redux-thunk'
//Expose the store  
//applyMiddleware is the middle position using thunk
export default createStore(countReducer,applyMiddleware(thunk))

(2) Create reducers.js

  • 1. This file is used to create a reducer that serves the Count component. The essence of a reducer is a function
  • 2. The reducer function will receive two parameters: the previous state (preState) and the action object (action)
const initState = 0 //Initialization state export default function countReducer(preState=initState,action){
	// console.log(preState);
	//Get from the action object: type, data
	const {type,data} = action
	//Decide how to process data based on type switch (type) {
		case 'increment': //if it is to add return preState + data
		case 'decrement': //If it is a decrease, return preState - data
		default:
			return preState
	}
}

(3) Introduce store.subscribe

Mainly use subscribe to monitor each modification in the store

// public index.js
import store from './redux/store'

//subscribe will update the data when the data in the store changes. Writing it here allows the global store.subscribe(()=>{
	ReactDOM.render(<App/>,document.getElementById('root'))
})

(4) Introducing react-redux

react-redux is a library encapsulated by the author of redux. It is a third-party module that further simplifies Redux and provides some additional APIs (such as: Provider, connect, etc.). Using it can better organize and manage our code and make it more convenient to use Redux in React.

Download react-redux

Create count file

//Import Count UI component import CountUI from '../../components/Count'

//Introduce connect to connect UI components and redux
import {connect} from 'react-redux'

-------------------------------------------------------------
/* 
	1. The mapStateToProps function returns an object;
	2. The key in the returned object is used as the key passed to the UI component props, and the value is used as the value passed to the UI component props
	3.mapStateToProps is used to pass state*/
function mapStateToProps(state){
	return {count:state}
}
-----------------------------------------------------------------
/* 
	1. The mapDispatchToProps function returns an object;
	2. The key in the returned object is used as the key passed to the UI component props, and the value is used as the value passed to the UI component props
	3.mapDispatchToProps is used to pass the operation status method*/
function mapDispatchToProps(dispatch){
	return {
		jia:number => dispatch(createIncrementAction(number)),
		jian:number => dispatch(createDecrementAction(number)),
		jiaAsync:(number,time) => dispatch(createIncrementAsyncAction(number,time)),
	}
}
//Use connect()() to create and expose a Count container component export default connect(mapStateToProps,mapDispatchToProps)(CountUI)
//Improved export default connect(
	state => ({count:state}),
	
	//General writing of mapDispatchToProps /* dispatch => ({
		jia:number => dispatch(createIncrementAction(number)),
		jian:number => dispatch(createDecrementAction(number)),
		jiaAsync:(number,time) => dispatch(createIncrementAsyncAction(number,time)),
	}) */

	//Shorthand for mapDispatchToProps {
		jia:createIncrementAction,
		jian:createDecrementAction,
		jiaAsync:createIncrementAsyncAction,
	}
)(Count)


Generate action objects and expose them separately

/* 
	This file is specifically used to generate action objects for the Count component*/
import {INCREMENT,DECREMENT} from '../constant'

//Synchronous action means that the value of the action is a general object of type Object export const increment = data => ({type:INCREMENT,data})
export const decrement = data => ({type:DECREMENT,data})

//Asynchronous action means that the value of action is a function. Asynchronous action usually calls synchronous action, but asynchronous action is not required.
export const incrementAsync = (data, time) => {
	return (dispatch)=>{
		setTimeout(()=>{
			dispatch(increment(data))
		},time)
	}
}

This concludes this article on the working principle and usage of redux. I hope it will be helpful for everyone’s study, and I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Detailed explanation of the usage and principle analysis of connect in react-redux
  • Detailed explanation of JavaScript state container Redux
  • Understand the initial use of redux in react in one article

<<:  Some simple implementation codes of the form element take registration as an example

>>:  SQL IDENTITY_INSERT case study

Recommend

Steps to modify the MySQL database data file path under Linux

After installing the MySQL database using the rpm...

Introduction to the use of common Dockerfile commands

Table of contents 01 CMD 02 ENTRYPOINT 03 WORKDIR...

What hidden attributes in the form can be submitted with the form

The form elements with visibility=hidden and displ...

MySQL 8.0.20 Installation Tutorial with Pictures and Text (Windows 64-bit)

1: Download from mysql official website https://d...

Detailed explanation of how to reduce memory usage in MySql

Preface By default, MySQL will initialize a large...

JavaScript implementation of carousel example

This article shares the specific code for JavaScr...

Detailed explanation of how to configure Nginx web server sample code

Overview Today we will mainly share how to config...

CSS web page responsive layout to automatically adapt to PC/Pad/Phone devices

Preface There are many devices nowadays, includin...

Two ways to implement text stroke in CSS3 (summary)

question Recently I encountered a requirement to ...

Sample code for implementing dark mode with CSS variables

Recently, WeChat was forced by Apple to develop a...

In-depth understanding of Vue-cli4 routing configuration

Table of contents Preface - Vue Routing 1. The mo...

Implementation of docker view container log command

Why should we read the log? For example, if the c...

Detailed explanation of how to use join to optimize SQL in MySQL

0. Prepare relevant tables for the following test...