React

如何在 Redux 中使用中间件

2021-09-18  本文已影响0人  CondorHero
如何在 Redux 中使用中间件.png

目录

中间件介绍

Redux 是 React 最流行的状态管理库之一。React 中间件是描述 dispatch 一个 action 到 reducer 之间的一个状态。

如果你想对 Redux 进行扩展,通过中间件是比较推荐的方法。

中间件最常用于日志记录、报告崩溃、与 API 通信等。

你可以在 npm 中找到很多开箱即用的中间件,并不需要我们去封装,但是我们可以稍微研究下 applyMiddleware 的使用,以此更加熟练的使用第三方插件包。

例如,我们自己实现一个简单的 redux-logger 中间件,它可以用于记录 action 操作和状态。

自定义 redux-logger 中间件

目标:我们写个小小的加法器,然后通过 logger 打印出 action 和 state。

自定义 redux-logger 中间件
import { createStore } from 'redux'

function counter(state, action) {
  switch (action.type) {
    case 'ADD':
      return state + 1;
    default:
      return state
  }
}

export const store = createStore(counter, 0)

一个简单的加加计数器就实现了,为了实现自定义中间件,我们需要知道 createStore 的第三个参数就是定义中间件的位置,同时需要 applyMiddleware(...middleware) 的配合。

enhancer = applyMiddleware(...middleware);
createStore(reducer, [preloadedState], [enhancer]);

OK ,接下来每个中间件就是一个函数,这个函数接收 store 作为参数(store 包含 dispatch 和 getState ,你也就可以对其进行解构访问)并返回一个函数。

返回的函数接收中间件的 next 方法,功能类似 dispatch,并期望返回一个 action 函数。

把上面的废话抽象成代码就是:

const logger = ({ dispatch, getState }) => next => action => {
  // Do the work and call "next(action)"
  next(action);
};

函数暴露出的 API 我们都拿到了,接下来就是实现了:

const logger = ({ getState }) => next => action => {
    // Log the current action
    console.log("Dispatching:", action);

    /*
    Call when middleware has done its job 
    To send the action to a reducer or the next middleware
    */
    next(action);

    // Log the new state after the action is executed
    console.log("Next state:", getState());
};

然后,将 Middleware 传递给 applyMiddleware(...middleware) 函数:

export const store = createStore(counter, 0, applyMiddleware(logger))

最后,计数器从零加到一会控制台打印出如下结果:

概括

在本文中,我们了解了什么是中间件,如何在 Redux 中创建自定义中间件,以及如何使用 applyMiddleware(...middleware) 方法写一个中间件。

上一篇下一篇

猜你喜欢

热点阅读