search
HomeWeb Front-endJS TutorialHow to use react+redux
How to use react+reduxJun 11, 2018 am 11:55 AM
reactreduxmiddleware

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)
    })

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

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)));

From here you can actually know what middleware looks like:

Basic form of middleware:

const MiddleWare = store => next => action => {
  ...
}

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);

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

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'));

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)
}

自定义中间件:很多时候网上的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'});
    }
  }
};

相信看了本文案例你已经掌握了方法,更多精彩请关注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
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
CodeIgniter中间件:加速应用程序的响应速度和页面渲染CodeIgniter中间件:加速应用程序的响应速度和页面渲染Jul 28, 2023 pm 06:51 PM

CodeIgniter中间件:加速应用程序的响应速度和页面渲染概述:随着网络应用程序的复杂性和交互性不断增长,开发人员需要使用更加高效和可扩展的解决方案来提高应用程序的性能和响应速度。CodeIgniter(CI)是一种基于PHP的轻量级框架,提供了许多有用的功能,其中之一就是中间件。中间件是在请求到达控制器之前或之后执行的一系列任务。这篇文章将介绍如何使用

使用Slim框架中间件实现国际短信发送和接收功能使用Slim框架中间件实现国际短信发送和接收功能Jul 28, 2023 pm 02:48 PM

使用Slim框架中间件实现国际短信发送和接收功能在现代社会中,短信已成为人们日常生活中重要的沟通工具之一。而随着国际交流的增加,国际短信发送和接收功能也日益受到重视。本文将介绍如何使用Slim框架中间件来实现国际短信发送和接收的功能。Slim是一个轻量级的PHP微框架,它提供了简单而强大的路由功能,非常适合用于快速开发小型API应用。同时,Slim也支持使用

使用Slim框架中间件实现二维码生成和扫描的功能使用Slim框架中间件实现二维码生成和扫描的功能Jul 28, 2023 pm 05:33 PM

使用Slim框架中间件实现二维码生成和扫描的功能简介:在现代社会,二维码已经成为广泛应用的一种信息传递方式。许多应用程序和网站都提供了二维码的生成和扫描功能。本文将介绍如何使用Slim框架的中间件来实现二维码的生成和扫描功能。安装Slim框架:首先,我们需要安装Slim框架。在终端中执行以下命令:composerrequireslim/slim生成二维码

Laravel中间件:为应用程序添加数据库查询和性能监控Laravel中间件:为应用程序添加数据库查询和性能监控Jul 28, 2023 pm 02:53 PM

Laravel中间件:为应用程序添加数据库查询和性能监控导言:在开发Web应用程序时,数据查询和性能监控是非常重要的。Laravel提供了一种方便的方式来处理这些需求,即中间件。中间件是在请求和响应之间进行处理的一种技术,它可以在请求到达控制器之前或响应返回给用户之后执行一些逻辑。本文将介绍如何使用Laravel中间件来实现数据库查询和性能监控。一、创建中间

银河麒麟系统安装中间件银河麒麟系统安装中间件Jun 12, 2023 am 11:13 AM

现在越来越多的企业级应用需要运行在国产化环境中,本文介绍下我们产品使用的中间件在国产操作系统银河麒麟的安装(不一定是最优方式,但能用)。包含;Nginx、Redis、RabbitMQ、MongoDB、dotNETCore。下图是银河麒麟服务器的信息:想要顺利安装需要确保:1、服务器能访问网络。想要完全离线的方式安装会更复杂,需要进一步研究。2、修改yum源。使用vi/etc/yum.repos.d/kylin_aarch64.repo来设置yum源,文件内容如下:###KylinLinuxAdv

Symfony框架中间件:提供错误处理和异常管理功能Symfony框架中间件:提供错误处理和异常管理功能Jul 28, 2023 pm 01:45 PM

Symfony框架中间件:提供错误处理和异常管理功能当我们在开发应用程序时,经常会遇到错误和异常的情况。为了优化用户体验和提供更好的开发者工具,Symfony框架提供了强大的错误处理和异常管理功能。在本文中,我们将介绍Symfony框架中间件的使用和示例代码。Symfony框架中的错误处理和异常管理功能主要通过中间件来实现。中间件是一个特殊的功能组件,用于在

CakePHP中间件:快速构建可扩展的Web应用程序CakePHP中间件:快速构建可扩展的Web应用程序Jul 28, 2023 am 11:33 AM

CakePHP中间件:快速构建可扩展的Web应用程序概述:CakePHP是一个流行的PHP框架,被广泛应用于Web应用程序的开发。其提供了许多功能强大的工具和功能,其中包括中间件。中间件可以帮助我们快速构建和扩展Web应用程序,提高代码的可读性和可维护性。什么是中间件:中间件是在请求被派发给控制器之前或之后执行的一系列操作。它们可以完成许多任务,如身份验证、

使用Yii框架中间件加密和解密敏感数据使用Yii框架中间件加密和解密敏感数据Jul 28, 2023 pm 07:12 PM

使用Yii框架中间件加密和解密敏感数据引言:在现代的互联网应用中,隐私和数据安全是非常重要的问题。为了确保用户的敏感数据不被未经授权的访问者获取,我们需要对这些数据进行加密。Yii框架为我们提供了一种简单且有效的方法来实现加密和解密敏感数据的功能。在本文中,我们将介绍如何使用Yii框架的中间件来实现这一目标。Yii框架简介Yii框架是一个高性能的PHP框架,

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software