React's Redux (3) middleware and asynchrony

1. Why use middleware

As we can see from the previous two articles, the process of updating the state in Redux is: action -> reducer -> new state.
So here comes the problem. Every time an action is triggered (dispatch). The reducer will update the store synchronously. In the actual development of projects, there are many requirements that need to obtain asynchronous data through interfaces and other forms before performing update operations. How to update the store asynchronously?
New tools are needed here: middleware middleware

What are the middleware

Redux itself does not provide many Apis and functions, but it provides a middleware (plug-in) mechanism, which can use middleware provided by a third party or write a middleware to enhance the functions of Redux. For example, you can use redux- The logger is a middleware to record actions and the state before and after each action, use redux-undo to cancel/redo actions, use redux-persist-store to persist the store, and so on.

Three middleware to solve asynchronous action

To implement asynchronous actions, there are multiple ready-made middlewares to choose from. Here, we choose the redux-thunk middleware used in the official document to implement it.
Redux-thunk is an upgrade of dispatch. The original dispatch method will pass the object to the store after receiving the object, but if the redux-thunk middleware is passed to dispatch is a function, then the function will not be passed directly For the store, the function will be executed first. After the execution is completed, when the store needs to be called, this function will call the store again.
1. Install redux-thunk

npm i redux-thunk -S

2.store.js

import {
    
     applyMiddleware, createStore } from 'redux';
import createLogger from 'redux-logger';
const logger = createLogger();

const store = createStore(
  reducer,
  initial_state,
  applyMiddleware(thunk, promise, logger)
);
export default store;

The three parameters of the applyMiddleware method are three middlewares. Some middlewares have order requirements. It is best to check the documentation before use. For example, the above logger must be placed at the end, otherwise the output result will be incorrect.
3. Asynchronous action

export const ACTION_INIT_LIST = value => {
    
    
  return {
    
    
    type: CHANGE_VALUE,
    value
  }
}
//利用redux-thunk 返回方法
export const ACTION_METHOD_INIT = () => {
    
    
  return dispatch => {
    
    
    axios.get('/api/data1').then(res => {
    
    
      console.log(res.data)
      let value = res.data //获取到数据
      let result = ACTION_INIT_LIST(value) //把数据封装到actions里面
      dispatch(result) //然后发射出去
    })
  }
}

Four configuration redux browser plug-in

When creating a store, the development environment will link to redux-devtool. During this linking process, a parameter can be passed to name the current store instance.

import {
    
     createStore, applyMiddleware, compose } from 'redux'
import thunk from 'redux-thunk'
import reducer from './reducer'
const middleware = [thunk]
const composeEnhancers =
  typeof window === 'object' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
    ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
    
    })
    : compose

const enhancer = composeEnhancers(
  applyMiddleware(...middleware)
  // other store enhancers if any
)
const store = createStore(reducer, enhancer)

export default store

You can find the corresponding column in the developer tool of chrome
Please add a picture description

Guess you like

Origin blog.csdn.net/LittleMoon_lyy/article/details/124563684