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

Example of implementing todo application with Vue

background First of all, I would like to state th...

MySQL index leftmost principle example code

Preface I was recently reading about MySQL indexe...

How to implement mask layer in HTML How to use mask layer in HTML

Using mask layers in web pages can prevent repeat...

MySQL 8.0.18 Installation Configuration Optimization Tutorial

Mysql installation, configuration, and optimizati...

Four solutions for using setTimeout in JS for loop

Table of contents Overview Solution 1: Closures S...

How to use CocosCreator object pool

Table of contents Preface: Specific operations St...

Comprehensive analysis of MySql master-slave replication mechanism

Table of contents Master-slave replication mechan...

Creation, constraints and deletion of foreign keys in MySQL

Preface After MySQL version 3.23.44, InnoDB engin...

Automatic failover of slave nodes in replication architecture in MySQL 8.0.23

I have been in contact with MGR for some time. Wi...

React+TypeScript project construction case explanation

React project building can be very simple, but if...

How to use vite to build vue3 application

1. Installation Tip: There is currently no offici...

Simple example of HTML checkbox and radio style beautification

Simple example of HTML checkbox and radio style b...

HTML table markup tutorial (22): row border color attribute BORDERCOLORLIGHT

Within rows, light border colors can be defined i...

Detailed explanation of Nginx Rewrite usage scenarios and code examples

Nginx Rewrite usage scenarios 1. URL address jump...