Home > Web Front-end > JS Tutorial > body text

A brief introduction to the use of react redux middleware

亚连
Release: 2018-05-26 14:29:39
Original
1779 people have browsed it

This article mainly introduces the use of redux middleware. Now I will share it with you and give you a reference.

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 enhanced through indirection or adding middleware. In addition to the ability to dispatch, yes redux has asynchronous capabilities;

Generally speaking, there are two ways for redux to handle asynchronous processing: 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 the data to the state in the original way. However, the disadvantage is that each call will write a lot of data. 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

Just a dozen lines of code, but it contains a lot of subtleties. The blogger chose three of them to analyze the subtleties:

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

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: In fact, it is MiddleWareAPI;

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

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

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

Difference:

next (far right middleware): In fact, it is the dispatch that actually triggers the reducer and changes the state. The dispatch and state here are synchronously related; the action here must be an object and cannot contain asynchronous information;

next (not the rightmost middleware): In fact, it is the function returned by the adjacent previous middleware (action => {...}); the action here is the action in the upper-level middleware next (action), the first middleware The action is the action in store.dispatch(action) in the project.

store.dispatch in middleware: It is actually used to plug in actions. It is understood here as the communication channel between actions and middleware.

Flowchart:

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

said here should be correct We have a general understanding of middleware. Next, we will introduce commonly used middleware and write one yourself.

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

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

Jquery具体实例介绍AJAX何时用,AJAX应该在什么地方用

js ajax加载时的进度条代码

有关Ajax跨域问题的两种解决方法

The above is the detailed content of A brief introduction to the use of react redux middleware. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template