react笔记(十六)—— redux中间件

137 阅读3分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第16天,点击查看活动详情

前言

大家好呀,我是L同学。在上篇文章react笔记(十五)—— react-redux-基本使用中,我们学习了React-redux基本介绍、react-redux-基本使用、react-redux-useSelector、react-redux-useDispatch等相关知识点。在本篇文章中,我们将学习到Redux中间件介绍、中间件的触发时机、logger 中间件、redux-thunk-基本使用、使用 redux-thunk 中间件前后对比、redux-devtools-extension的使用等相关知识点。

Redux中间件介绍

默认情况下,Redux 自身只能处理同步数据流。但是在实际项目开发中,状态的更新、获取,通常是使用异步操作来实现。如何在 Redux 中进行异步操作呢?通过 Redux 中间件机制来实现。

中间件,可以理解为处理一个功能的中间环节。中间件的优势是可以串联、组合,在一个项目中使用多个中间件。Redux 中间件用来处理 状态 更新,也就是在 状态 更新的过程中,执行一系列的相应操作。

中间件的触发时机

Redux 中间件执行时机在 dispatching action 和 到达 reducer 之间。

  • 没有中间件:dispatch(action) => reducer
  • 使用中间件:dispatch(action) => 执行中间件代码 => reducer

原理封装了 redux 自己的 dispatch 方法。

  • 没有中间件:store.dispatch() 就是 Redux 库自己提供的 dispatch 方法,用来发起状态更新
  • 使用中间件:store.dispatch() 就是 中间件 封装处理后的 dispatch,但是,最终一定会调用 Redux 库自己提供的 dispatch 方法

logger 中间件

logger 中间件使用步骤:

  1. 安装:yarn add redux-logger
  2. 导入 redux-logger
  3. 从 redux 中导入 applyMiddleware 函数
  4. 将 applyMiddleware() 调用作为 createStore 函数的第二个参数
  5. 调用 applyMiddleware 函数时,将 logger 作为参数传入

调用 store.dispatch() 查看 logger 中间件记录的日志信息。

import { createStore, applyMiddleware } from 'redux'
import logger from 'redux-logger'
import rootReducer from './reducers'
const store = createStore(rootReducer, applyMiddleware(logger))

redux-thunk-基本使用

redux-thunk中间件可以处理函数形式的 action。因此,在函数形式的 action 中就可以执行异步操作代码,完成异步操作。

redux-thunk使用步骤:

  1. 安装:yarn add redux-thunk
  2. 导入 redux-thunk
  3. 将 thunk 添加到中间件列表中
  4. 修改 action creator,返回一个函数

在函数形式的 action 中执行异步操作。在异步操作成功后,分发 action 更新状态。

// store/index.js
import thunk from 'redux-thunk'
// 将 thunk 添加到中间件列表中
const store = createStore(rootReducer, applyMiddleware(thunk, logger))

export const clearTodo = () => {
  return (dispatch) => {
    // 处理异步的代码
    setTimeout(() => {
      dispatch({
        type: CLEAR_TODO
      })
    }, 1000)
  }
}

使用 redux-thunk 中间件前后对比

不使用 redux-thunk 中间件:

export const delTodo = (id) => ({type: DEL_TODO, id})

使用 redux-thunk 中间件:

export const delTodo = (id) => {
    return dispatch => {
        setTimeout(function() {
            dispatch({type: DEL_TODO, id})
        }, 1000)
    }
}

redux-devtools-extension的使用

开发react项目时,通过chrome开发者工具调试跟踪redux状态。保证浏览器安装了redux的开发者工具。

使用步骤:

  1. 通过包管理器在项目中安装 yarn add redux-devtools-extension
  2. 在index.js中进行配置和导入
  3. 启动react项目,打开chrome开发者工具,测试
import { createStore, applyMiddleware } from 'redux'
import reducer from './reducers'
// import logger from 'redux-logger'
import thunk from 'redux-thunk'
import { composeWithDevTools } from 'redux-devtools-extension'
const store = createStore(reducer, composeWithDevTools(applyMiddleware(thunk)))

export default store