search
HomeWeb Front-endJS TutorialDetailed introduction to redux asynchronous operations (code example)
Detailed introduction to redux asynchronous operations (code example)Nov 20, 2018 pm 02:38 PM
javascriptreact.jsreduxAsynchronous programming

This article brings you a detailed introduction (code example) about redux asynchronous operations. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. Redux basics

redux

  • Through dispatch(action) - > Middleware -> reducer processes data -> Change store -> Use subscribe() to monitor store changes and update views to manage state

  • Store all states in one store The

  • reducer in the object is a pure function, and the asynchronous operation contains side effects due to the uncertainty of the result, so special handling is required

# #react-reduxContainer component, responsible for managing data and business logic, not responsible for UI presentation
UI component, provides UI presentation, stateless means not using this.state, all states are provided by this.props
Container components are generated by connect. Each time the store changes, connect will be called. connect receives two parameters: mapStateToProps, mapDispatchToProps
mapStateToProps, maps the state to the props of the UI component
mapDispatchToProps, maps the dispatch method to the UI The props of the component
Provider component uses the content API to pass the store from the top level to each layer of component for use by connect

2. Redux handles asynchronous middleware

redux-thunkredux-thunk middleware allows action to be a method
After receiving the action, the middleware will execute the action method and provide the result to the reducer
Action confusion leads to difficulty Maintenance

redux-sagasaga will listen to the action and perform Effects operations based on this action
Effects provides flexible APIs, including blocking and non-blocking calls, cancellation, waiting, race and other operations
Convenient to isolate and perform asynchronous operations, and easy to test

3. redux-request-async-middleware

Let’s start with the asynchronous action in the redux document , each interface call requires dispatching three synchronization actions, which are:

An action that notifies the reducer that the request has started. For this kind of action, the reducer may switch the isFetching tag in the state. This tells the UI to display the loading interface.
An action that notifies the reducer that the request is successful. For this kind of action, the reducer may merge the new data received into the state and reset isFetching. The UI will hide the loading interface and display the received data.
An action that notifies the reducer that the request failed. For this kind of action, the reducer may reset isFetching. In addition, some reducers will save these failure information and display it in the UI.
That is, an interface is initiated like this.

dispatch(fetchPostsRequest(subject));
fetch(url).then(res => {
  dispatch(fetchPostsSuccess(subject, res));
}).catch(e => {
  dispatch(fetchPostsFailure(subject, e));
})
Just encapsulates this operation into middleware. The special thing is:

  • Common to all asynchronous requests These three actions

  • Use subject to distinguish which request it is

  • Put all results in store.requests

Middleware source code

export const reduxRequest = store => next => action => {
  let result = next(action);
  let { type, subject, model } = action;
  let _next = action.next;
  if(type === FETCH_POSTS_REQUEST) {
    model().then(response => {
      _next && _next(response);
      store.dispatch(fetchPostsSuccess(subject, response));
    }).catch(error => {
      console.error(error);
      store.dispatch(fetchPostsFailure(subject, error));
    });
  }
  return result
};/
  • Same as redux-thunk, put the method into the action

  • Middle The software intercepts the FETCH_POSTS_REQUEST action and performs asynchronous processing

reducer source code

export const requests = (state = {}, action) => {
  switch (action.type) {
    case FETCH_POSTS_REQUEST:
      return assign({},
        state,
        {
          [action.subject]: {
            isFetching: true,
            state: 'loading',
            subject: action.subject,
            response: null,
            error: null,
          }
        }
      );
    case FETCH_POSTS_FAILURE:
      return assign({},
        state,
        {
          [action.subject]: {
            isFetching: false,
            state: 'error',
            subject: action.subject,
            response: state[action.subject].response,
            error: action.error,
          }
        }
      );
    case FETCH_POSTS_SUCCESS:
      return assign({},
        state,
        {
          [action.subject]: {
            isFetching: false,
            state: 'success',
            subject: action.subject,
            response: action.response,
          }
        }
      );
    case FETCH_POSTS_CLEAR:
      return assign({},
        state,
        {
          [action.subject]: {
            isFetching: false,
            state: 'cleared',
            subject: null,
            response: null,
            error: null,
          }
        }
      )
      return state;
  }
}
  • Put the result into the response corresponding to the subject, if it is wrong Put the error information into error

  • isFetching indicates the current request status

  • In addition, the current state state and subject information are also added

Encapsulate the request

const request = (subject, model, next) => {
  _dispatch(fetchPostsRequest(subject, model, next));
  return true;
};
  • Write a method to initiate the FETCH_POSTS_REQUEST action

  • In other words, write When making a request, you no longer need to worry about the action. Simply call the request method

to encapsulate the result.

const getResponse = state =>
  state
  && state.response !== null
  && state.response;
 
const getLoading = (states = []) =>
  states.reduce((pre, cur) =>
    pre || (cur && cur.isFetching)
    , false)
  || false;
  1. You can obtain the result and multiple The loading status under the request

  2. If there are more operations or formats, you can continue to encapsulate it, such as the list

4. Summary

  1. Using redux for state management, there is no need to write the complex logic of redux, minimizing the complexity of asynchronous operations

  2. Suitable for projects where the front end processes and stores data through interfaces

  3. The interface is processed by redux, while the view component is processed by the internal state, while only simple interfaces are exposed externally To operate, separate the business layer and the view layer

  4. Compared with react 16.3 new content API, the advantage of redux lies in the hot-insertion middleware and pure function reducer writing method

The above is the detailed content of Detailed introduction to redux asynchronous operations (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
PHP中如何使用ReactPHP进行异步编程PHP中如何使用ReactPHP进行异步编程Jun 27, 2023 am 09:14 AM

随着Web应用程序变得越来越复杂,程序员不得不采用异步编程来处理大量请求和I/O操作。PHP:HypertextPreprocessor也不例外。为了满足这一需求,ReactPHP已经成为目前最受欢迎的PHP异步编程框架之一。在本文中,将讨论如何在PHP中使用ReactPHP进行异步编程。1.ReactPHP简介ReactPHP是一个基于事件驱动编程

JavaScript函数异步编程:处理复杂任务的必备技巧JavaScript函数异步编程:处理复杂任务的必备技巧Nov 18, 2023 am 10:06 AM

JavaScript函数异步编程:处理复杂任务的必备技巧引言:在现代前端开发中,处理复杂任务已经成为了必不可少的一部分。而JavaScript函数异步编程技巧则是解决这些复杂任务的关键。本文将介绍JavaScript函数异步编程的基本概念和常用的实践方法,并提供具体的代码示例,帮助读者更好地理解和使用这些技巧。一、异步编程的基本概念在传统的同步编程中,代码按

如何在PHP中实现异步消息处理如何在PHP中实现异步消息处理Jul 10, 2023 am 08:19 AM

如何在PHP中实现异步消息处理引言:在现代的Web应用程序中,异步消息处理变得越来越重要。异步消息处理可以提高系统的性能和可扩展性,并改善用户体验。PHP作为一种常用的服务器端编程语言,也可以通过一些技术来实现异步消息处理。在本文中,我们将介绍一些PHP中实现异步消息处理的方法,并提供代码示例。使用消息队列消息队列是一种解耦系统组件的方式,它允许不同的组件在

深入理解PHP8的新特性:如何高效使用异步编程和代码?深入理解PHP8的新特性:如何高效使用异步编程和代码?Sep 11, 2023 pm 01:52 PM

深入理解PHP8的新特性:如何高效使用异步编程和代码?PHP8是PHP编程语言的最新主要版本,带来了许多令人兴奋的新特性和改进。其中最突出的特性之一是对异步编程的支持。异步编程允许我们在处理并发任务时提高性能和响应能力。本文将深入探讨PHP8的异步编程特性,并介绍如何高效地使用它们。首先,让我们了解一下什么是异步编程。在传统的同步编程模型中,代码按照线性的顺

如何使用PHP和ReactPHP实现异步编程如何使用PHP和ReactPHP实现异步编程May 11, 2023 pm 02:00 PM

随着互联网应用场景的不断发展,人们对Web应用的要求也越来越高。为了提高Web应用的性能和响应速度,异步编程已经成为现代Web应用开发不可或缺的一部分。PHP是一门广泛使用的Web开发语言,而ReactPHP则是一个基于PHP的异步编程框架。本篇文章将介绍如何使用PHP和ReactPHP实现异步编程。一、什么是异步编程?在编程中,同步和异步是两种常用的编程方

前往Golang学习之Web服务端的异步编程模式前往Golang学习之Web服务端的异步编程模式Jun 24, 2023 am 10:52 AM

随着互联网技术的快速发展,Web服务端的开发成为了当前互联网行业的热门话题。而Golang作为一门新兴的编程语言,凭借其高效、并发的特性,也成为了Web服务端开发的首选语言之一。本文将会介绍GolangWeb服务端的异步编程模式,旨在帮助读者更好地掌握Golang在Web服务端开发中的应用。一、什么是异步编程模式异步编程模式是指程序的执行不是按照程序的顺序

如何在Go语言中实现异步编程如何在Go语言中实现异步编程Jun 04, 2023 am 08:10 AM

随着互联网技术的不断发展,高并发高可用的需求越来越强烈。而异步编程是提高程序运行效率和响应能力的有效手段之一。Go语言作为一种新兴的编程语言,天生支持并发和异步编程,极大地方便了程序员的开发工作。本文将介绍如何在Go语言中实现异步编程。一、Go语言中的goroutineGo语言提供了goroutine机制,可以轻松地实现并发和异步操作。goroutine是一

探究Swoole异步编程中的IO信号处理探究Swoole异步编程中的IO信号处理Jun 13, 2023 pm 05:54 PM

Swoole是一个很流行的基于PHP语言实现的高性能网络通信框架,它提供了诸如异步IO、多进程、协程等功能,极大的提升了基于PHP语言开发网络应用程序的效率和性能。其中,IO信号处理是Swoole异步编程中的一个非常关键的部分,本文就来探究一下Swoole异步编程中的IO信号处理。一、IO信号处理的概念在日常工作中,我们经常需要监听来自各种设备或系统的输入输

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尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools