Home Web Front-end JS Tutorial How to use react+redux

How to use react+redux

Jun 11, 2018 am 11:55 AM
react redux middleware

This time I will show you how to use react redux and what are the precautions for using react redux. The following is a practical case, let's take a look.

Students who have used react all know the existence of redux. Redux is a front-end warehouse used to store data and a framework for adding, deleting, modifying and checking the warehouse. It is not only applicable to react , also used in other front-end frameworks. Anyone who has studied the redux source code thinks that the source code is very sophisticated, and this blog post will introduce the processing of middleware in redux.

Before talking about redux middleware, let’s use two pictures to briefly introduce the basic principles of redux:

The picture shows the basic process of redux. I won’t go into details here.

Generally, not only redux is used in react, but also react-redux:

react-redux will not be detailed here.

redux middleware

Under normal circumstances, redux does not have the ability to handle asynchronous requests. Young communication is done indirectly or by adding middleware to strengthen dispatch. The ability is that redux has the ability to be asynchronous;

Generally speaking, there are two ways for redux to handle asynchrony: indirect method and middleware method;

Indirect method:

The indirect method is to customize the asynchronous behavior and retain the dispatch synchronization function.
Idea: The asynchronously returned result is stuffed into the action, and then synchronized to the reduce through dispatch, and then the state is changed;

demo:

request.get(API)
    .then(d => {
      store.dispatch(type: xxx, playload: d)
    })
Copy after login

This method does not destroy the synchronization mechanism of dispatch. It uses dispatch to synchronize data to the state. However, the disadvantage is that each call will write a long paragraph.

Middleware method

The core part of the middleware method is the high-order function applyMiddleWare provided by redux, which returns a brand new store object through multiple layers of calls. The only difference between the new store object and the original object is that dispatch has the asynchronous function;

Source code:

const applyMiddleWare = (...middlewares) => createStore => (reducer, initState) =>{
  const store = createStore(reducer, initState);
  const _dispatch = store.dispatch;
  const MiddleWareAPI = {
    getState: store.getState,
    dispatch: action => _dispatch(action)  1)
  };
  const chain = [];
  chain = middlewares.map(middleware => {middleware(MiddleWareAPI)}); 2)
  let dispatch = compose(...chain)(store.dispatch);  3)
  return {
    dispatch,
    ...store
  }
}
Copy after login

It is just a dozen lines of code, but it contains many subtleties. Here, the blogger chose three of them to analyze their subtleties:

1) MiddleWareAPI is mainly inserted into middleware, and finally inserted into the action, so that the action can have the dispatch ability, and The main reason why anonymous functions are used here is because the store in MiddleWareAPI.dispatch must be consistent with the store finally returned by applyMiddleWare. It should be noted that MiddleWareAPI.dispatch does not really change the state. It can be understood as action and middleware. of a bridge.

2) The change is to insert MiddleWareAPI into all middleware, and then return a function, and the form of middleware will be mentioned later.

3) This is the most subtle point. Compose will inject the chain array from right to left into the previous middleware, while store.dispatch will inject into the rightmost middleware. In fact, compose can be understood as a reduce function here.

eg:

M = [M1,M2,M3] ----> M1(M2(M3(store.dispatch)));
Copy after login

From here you can actually know what middleware looks like:

Basic form of middleware:

const MiddleWare = store => next => action => {
  ...
}
Copy after login

Parameter explanation:

  1. store: Actually it is MiddleWareAPI;

  2. next: There are two situations here. If the middleware is changed to the rightmost part of the middlewares array, Then next is store.dispatch; otherwise it is the return value of a middleware on the adjacent left (the closure function is the action => {} function);

  3. ##action: OK It can be a function or an object containing a promise;

You may be a little confused here, and the confusion may be that you can’t tell the difference between next and store.dispatch;

Difference:

next (the rightmost middleware): It is actually the dispatch that actually triggers the reducer and changes the state. The dispatch and state here are synchronized; the action here must be an object and cannot contain Asynchronous information;

next(非最右边的中间件):其实就是相邻前一个中间件返回的函数(action => {...});这里的action就是上一级中间件next(action)中的action,第一个中间件的action就是项目中store.dispatch(action)中的action。

中间件中的store.dispatch:其实就是用来塞进action的,这里就理解为action和中间件通信的渠道吧。

流程图:

demo:

export const MiddleForTest = store => next => action => {
  if (typeof action === 'function') {
    action(store);
  } else {
    next(action);
  }
};
export const MiddleForTestTwo = store => next => action => {
  next(action);
};
export function AjaxAction(store) {
  setTimeout(function () {
    store.dispatch({
      type: 'up',
      playload: '异步信息'
    })
  }, 1000)
}
store.dispatch(AjaxAction);
Copy after login

说道这里应该会对中间件有个大致的认识,接下来介绍一下常用的中间件以及自己写一个中间件。

redux-thunk:主要是适用于action是一个函数的情况,它是对原有的中间件模式再封装多一层,原则上是支持promise为主的action函数;

export function AjaxThunk (url, type) {
  return dispatch => {
    Ajax(url)
      .then(d => {
        dispatch({
          type,
          playload: d
        })
      })
  }
}
store.dispatch(AjaxThunk(url1, 'add'));
Copy after login

redux-promise:主要就是针对action对象,action对象是一个promise的异步请求函数:

它的大概实现思路是:

const promiseAction = store => next => action => {
    const {type, playload} = action;
    if (playload && typeof playload.then === 'function') {
      playload.then(result => {
        store.dispatch({type, playload: result});
      }).catch(e => {})
    } else {
      next(action);
    }
}
action = {
 type: 'xxx',
 playload: Ajax(url)
}
Copy after login

自定义中间件:很多时候网上的redux中间件可能不太符合项目中的需要,所以这时候可以自己写一套适合项目的中间件,以下指示本博主的一个demo,形式不唯一:

export const PromiseWares = store => next => action => {
  next({type: 'right', playload: 'loading'});
  if (typeof action === 'function') {
    const {dispatch} = store;
    action(dispatch);
  } else {
    const {type, playload} = action;
    if (playload && typeof playload.then === 'function') {
      playload.then(result => {
        store.dispatch({type, playload: result});
      }).catch(e => {})
    } else {
      next(action);
      next({type: 'right', playload: 'noLoading'});
    }
  }
};
Copy after login

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

assets与static使用案例剖析

JS使用createElement()动态添加HTML

The above is the detailed content of How to use react+redux. 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)

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.

PHP, Vue and React: How to choose the most suitable front-end framework? PHP, Vue and React: How to choose the most suitable front-end framework? Mar 15, 2024 pm 05:48 PM

PHP, Vue and React: How to choose the most suitable front-end framework? With the continuous development of Internet technology, front-end frameworks play a vital role in Web development. PHP, Vue and React are three representative front-end frameworks, each with its own unique characteristics and advantages. When choosing which front-end framework to use, developers need to make an informed decision based on project needs, team skills, and personal preferences. This article will compare the characteristics and uses of the three front-end frameworks PHP, Vue and React.

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.

Integration of Java framework and front-end React framework Integration of Java framework and front-end React framework Jun 01, 2024 pm 03:16 PM

Integration of Java framework and React framework: Steps: Set up the back-end Java framework. Create project structure. Configure build tools. Create React applications. Write REST API endpoints. Configure the communication mechanism. Practical case (SpringBoot+React): Java code: Define RESTfulAPI controller. React code: Get and display the data returned by the API.

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 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?

How to use middleware for scheduled task scheduling in Laravel How to use middleware for scheduled task scheduling in Laravel Nov 02, 2023 pm 02:26 PM

How to use middleware for scheduled task scheduling in Laravel Introduction: Laravel is a popular PHP open source framework that provides convenient and powerful tools to develop web applications. One of the important features is scheduled tasks, which allows developers to run specific tasks at specified intervals. In this article, we will introduce how to use middleware to implement Laravel's scheduled task scheduling, and provide specific code examples. Environment Preparation Before starting, we need to make sure

How to use middleware for multi-language support in Laravel How to use middleware for multi-language support in Laravel Nov 03, 2023 pm 01:07 PM

Laravel is a widely used PHP framework that provides many convenient features and tools, including middleware that supports multiple languages. In this article, we will detail how to use middleware to implement Laravel's multi-language support and provide some specific code examples. Configuring the language pack First, we need to configure Laravel's language pack so that it can support multiple languages. In Laravel, language packages are usually placed in the resources/lang directory, where each language

See all articles