redux-中间件-理解中间件

912 阅读3分钟

目标

能够理解为什么需要redux中间件

问题

问题:获取数据时,如何发ajax拿数据,并保存到redux中?

方案1:在业务组件中发请求,拿到数据之后,再dispath

511.png

方案2:在业务组件中直接dispatch,在dispatch中发请求,然后保存redux。

3220.png

中间件

middleware。

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

  • 没有中间件:

    • dispatch(action) => reducer。用来发起状态更新

redux中间件-触发时机1.jpg

  • 使用中间件:

    • dispatch(action) => 执行中间件代码 => reducer。dispatch() 就是 中间件 封装处理后的 dispatch,但是,最终一定会调用 Redux 库自己提供的 dispatch 方法

redux中间件-触发时机2.jpg

小结

中间件是对原有功能的拓展

redux中间件的执行时机在dispatch之后,执行reducer逻辑之前

redux-thunk-基本使用

目标

掌握redux-thunk的使用,理解中间件的工作方式。

作用

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

拓展了功能,支持函数形式的 action

  • 之前

    • const action1 = {type: 'todos/add', payload: '学习redux'}
      dispatch(action1)
      
  • 之后

    • const action1 = async (dispatch) =>{
        const res = await 异步动作()
        dispatch({type: 'todos/add', payload: '学习redux'})
      }
      ​
      dispatch(action1)
      

步骤

  1. 安装:npm i redux-thunk

  2. 使用:在store/index.js

    1. 导入 redux-thunk , applyMiddleware

      import { createStore, applyMiddleware } from 'redux'
      import thunk from 'redux-thunk'
      
    2. 调用applyMiddleware将 thunk 添加到中间件列表中

      const store = createStore(rootReducer, applyMiddleware(thunk))

    3. 修改 action creator,返回一个函数,其形参就是redux的dispatch

      const addTodo = (name)=> {
        return async (dispatch) =>{
          const res = await 异步动作()
          dispatch({type: 'todos/add', payload: name})
        }
      }
      ​
      dispatch(addTodO('学习redux'))
      

示例

axios.post('www.fastmock.site/mock/74f9d7…')

中间件-redux-logger

目标

掌握redux-logger的使用,能查看redux的操作日志;

理解多个中间件的工作过程

步骤

  1. 安装:yarn add redux-logger

  2. 使用。store/index.js

    1. 导入 redux-logger
    2. 调用 applyMiddleware 函数时,将 logger 作为参数传入
import { createStore, applyMiddleware } from 'redux'
import logger from 'redux-logger'
import rootReducer from './reducers'
const store = createStore(rootReducer, applyMiddleware(logger))
  1. 测试效果。

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

redux-devtools-extension的使用

目标

开发react项目时,通过chrome开发者工具调试跟踪redux状态

先要安装 redux的开发者工具,再安装redux调试工具

文档 redux-devtools-extension

redux-devtools-extension

方便在浏览器中调试redux操作的工具

步骤

  1. 安装react开发者工具
  2. 在项目中安装redux调试工具,它是一个npm包。 npm i redux-devtools-extension -D
  3. 配置。在store/index.js中进行配置和导入
import { createStore, applyMiddleware } from 'redux'
import { composeWithDevTools } from 'redux-devtools-extension'
const store = createStore(reducer, composeWithDevTools(applyMiddleware(中间件..)))
​
export default store

效果

每一次redux的操作,就会有记录

image-20211113200834241.png

拓展-redux-thunk-中间件原理

function createThunkMiddleware(extraArgument) {
  // Redux 中间件的写法:const myMiddleware = store => next => action => { /* 此处写 中间件 的代码 */ }
  return ({ dispatch, getState }) => (next) => (action) => {
    // redux-thunk 的核心代码:
    // 判断 action 的类型是不是函数
    // 如果是函数,就调用该函数(action),并且传入了 dispatch 和 getState
    if (typeof action === 'function') {
      return action(dispatch, getState, extraArgument);
    }
    
    // 如果不是函数,就调用下一个中间件(next),将 action 传递过去
    // 如果没有其他中间件,那么,此处的 next 指的就是:Redux 自己的 dispatch 方法
    return next(action);
  };
}

\