Home Web Front-end JS Tutorial Detailed explanation of redux-thunk practical project cases

Detailed explanation of redux-thunk practical project cases

Jun 07, 2018 pm 02:55 PM
redux middleware

This time I will bring you a detailed explanation of the redux-thunk practical project case. What are the precautions for using redux-thunk practical project? The following is a practical case, let’s take a look.

The core concept of redux is actually very simple: store all the state that needs to be modified into the store, initiate an action to describe what happened, and use reducers to describe how the action changes the state tree. When creating a store, you need to pass in the reducer. What can really change the data in the store is the store.dispatch API.

1. Concept

After dispatching an action and before reaching the reducer, you need to use middleware to perform some additional operations. You can use Redux middleware for logging, creating crash reports, calling asynchronous interfaces or routing, and more.
In other words, middleware is an enhancement to store.dispatch()

2. Usage of middleware

import { applyMiddleware, createStore } from 'redux';
import thunk from 'redux-thunk';
const store = createStore(
  reducers, 
  applyMiddleware(thunk)
);
Copy after login

Introduce thunk middleware directly and put In the applyMiddleware method, passing in the createStore method completes the functional enhancement of store.dispatch(). That is, you can perform some asynchronous operations in the reducer.

3.applyMiddleware()

In fact, applyMiddleware is a native method of Redux, which combines all middleware into an array and executes them in sequence.

If there are too many middlewares, they can be passed in as parameters one after another

const store = createStore(
  reducers, 
  applyMiddleware(thunk, logger)
);
Copy after login

If you want to understand its evolution, you can go to the official documentation of redux: https://redux.js.org/advanced/middleware

4.redux-thunk

Analyze the source code of redux-thunk node_modules/redux-thunk/src/index.js

function createThunkMiddleware(extraArgument) {
 return ({ dispatch, getState }) => next => action => {
  if (typeof action === 'function') {
   return action(dispatch, getState, extraArgument);
  }
  return next(action);
 };
}
const thunk = createThunkMiddleware();
thunk.withExtraArgument = createThunkMiddleware;
export default thunk;
Copy after login

redux-thunk The middleware export default is the thunk passed by createThunkMiddleware(). Looking at the createThunkMiddleware function, it returns a curried function. The code we translate into ES5 is easier to read.

function createThunkMiddleware(extraArgument) {
  return function({ dispatch, getState }) {
    return function(next){
      return function(action){
        if (typeof action === 'function') {
          return action(dispatch, getState, extraArgument);
        }
        return next(action);
      };
    }
  }
}
Copy after login

With this look, we can see that the most important idea of ​​redux-thunk is that it can accept an action creator that returns a function. If the action creator returns a function, execute it. If not, execute it according to the original next(action).

Because this action creator can return a function, you can perform some asynchronous operations in this function.

For example:

export function addCount() {
  return {type: ADD_COUNT}
}
export function addCountAsync() {
  return dispatch => {
    setTimeout( () => {
      dispatch(addCount())
    },2000)
  }
}
Copy after login

The addCountAsync function returns a function, pass dispatch as the first parameter of the function, and perform asynchronous operations within the function.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to use JS to get the last 7 days and the last 3 days

Angular ng-animate and How to use ng-cookies within the project

The above is the detailed content of Detailed explanation of redux-thunk practical project cases. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement custom middleware in CodeIgniter How to implement custom middleware in CodeIgniter Jul 29, 2023 am 10:53 AM

How to implement custom middleware in CodeIgniter Introduction: In modern web development, middleware plays a vital role in applications. They can be used to perform some shared processing logic before or after the request reaches the controller. CodeIgniter, as a popular PHP framework, also supports the use of middleware. This article will introduce how to implement custom middleware in CodeIgniter and provide a simple code example. Middleware overview: Middleware is a kind of request

What is the principle of tomcat middleware What is the principle of tomcat middleware Dec 27, 2023 pm 04:40 PM

The principle of tomcat middleware is implemented based on Java Servlet and Java EE specifications. As a Servlet container, Tomcat is responsible for processing HTTP requests and responses and providing the running environment for Web applications. The principles of Tomcat middleware mainly involve: 1. Container model; 2. Component architecture; 3. Servlet processing mechanism; 4. Event listening and filters; 5. Configuration management; 6. Security; 7. Clustering and load balancing; 8. Connector technology; 9. Embedded mode, etc.

Implementing user authentication using middleware in the Slim framework Implementing user authentication using middleware in the Slim framework Jul 29, 2023 am 10:22 AM

Implementing user authentication using middleware in the Slim framework With the development of web applications, user authentication has become a crucial feature. In order to protect users' personal information and sensitive data, we need a reliable method to verify the user's identity. In this article, we will introduce how to implement user authentication using the Slim framework’s middleware. The Slim framework is a lightweight PHP framework that provides a simple and fast way to build web applications. One of the powerful features is the middle

How to handle form validation using middleware in Laravel How to handle form validation using middleware in Laravel Nov 02, 2023 pm 03:57 PM

How to use middleware to handle form validation in Laravel, specific code examples are required Introduction: Form validation is a very common task in Laravel. In order to ensure the validity and security of the data entered by users, we usually verify the data submitted in the form. Laravel provides a convenient form validation function and also supports the use of middleware to handle form validation. This article will introduce in detail how to use middleware to handle form validation in Laravel and provide specific code examples.

How to use middleware for data acceleration in Laravel How to use middleware for data acceleration in Laravel Nov 02, 2023 am 09:40 AM

How to use middleware for data acceleration in Laravel Introduction: When developing web applications using the Laravel framework, data acceleration is the key to improving application performance. Middleware is an important feature provided by Laravel that handles requests before they reach the controller or before the response is returned. This article will focus on how to use middleware to achieve data acceleration in Laravel and provide specific code examples. 1. What is middleware? Middleware is a mechanism in the Laravel framework. It is used

How to use middleware for response transformation in Laravel How to use middleware for response transformation in Laravel Nov 03, 2023 am 09:57 AM

How to use middleware for response conversion in Laravel Middleware is one of the very powerful and practical features in the Laravel framework. It allows us to process requests and responses before the request enters the controller or before the response is sent to the client. In this article, I will demonstrate how to use middleware for response transformation in Laravel. Before starting, make sure you have Laravel installed and a new project created. Now we will follow these steps: Create a new middleware Open

How to use middleware to set up cross-domain resource sharing (CORS) in the Slim framework How to use middleware to set up cross-domain resource sharing (CORS) in the Slim framework Jul 30, 2023 pm 08:34 PM

How to set up Cross-Origin Resource Sharing (CORS) using middleware in the Slim framework Cross-Origin Resource Sharing (CORS) is a mechanism that allows the server to set some additional information in the HTTP response header to tell the browser whether Allow cross-domain requests. In some projects with front-end and back-end separation, the CORS mechanism can be used to realize the front-end's cross-domain request for the back-end interface. When using the Slim framework to develop REST API, we can use middleware (Middleware)

How to use middleware for data recovery in Laravel How to use middleware for data recovery in Laravel Nov 02, 2023 pm 02:12 PM

Laravel is a popular PHP web application framework that provides many fast and easy ways to build efficient, secure and scalable web applications. When developing Laravel applications, we often need to consider the issue of data recovery, that is, how to recover data and ensure the normal operation of the application in the event of data loss or damage. In this article, we will introduce how to use Laravel middleware to implement data recovery functions and provide specific code examples. 1. What is Lara?

See all articles