深入Redux及其中间件

作者: 爱吃芋圆的小w | 来源:发表于2019-06-22 22:11 被阅读9次

1. Redux简介

  1. Redux的核心API主要有两个:createStore和reducer。
  • createStore
    createStore(reducers[, initialState])主要是用于生成store的,reducers必须传入,initialState是可选择是否传入的参数初始化状态。引用时:
    import { createStore } from 'redux'; 
    const store = createStore(reducers);
    
    其中创建的store又包含四个API:
  1. getState():获取 store 中当前的状态。
  2. dispatch(action):分发一个 action,并返回这个 action,这是唯一能改变 store 中数据的方式。
  3. subscribe(listener):注册一个监听者,它在 store 发生变化时被调用。
  4. replaceReducer(nextReducer):更新当前 store 里的 reducer,一般只会在开发模式中调用该方法。
  • reducer
    reducer主要负责响应action并修改数据, 它是一个函数,reducer(previousState, action) => newState,需要注意的是第一次执行的时候,并没有任何的 previousState,因此在这种特殊情况下需要返回一个定义好的 initialState。实际运用时:
      const initialState = { 
      todos: [], 
      };
      function todos(previousState = initialState, action) { 
      switch (action.type) {  
        case 'XXX': { 
        // 具体的业务逻辑
        } 
        default: 
        return previousState; 
      } 
      }
    
  1. 与React的绑定
    react-redux库提供了一个组件<Provider/>和一个方法connect()帮助 Redux 和 React 进行绑定。Provider 是整个应用最外层的 React 组件,它接受一个 store 作为 props。connect() 可以在整个React应用的任意组件中获取store中的数据。

2.Redux中间件

2.1 什么是中间件

传统的Redux单向数据流如图所示:


Redux单向数据流图

这样的单向数据流动存在很多问题,比如当调用的action发生改变时,就必须修改dispatch 或者 reducer,而且请求数据不是异步的,因此Redux中间件由此出现,它的自由组合,自由插拔的插件机制正好解决了这个问题,它的目的是增强dispatch,Redux运用中间件处理事件的流程如图所示:


Redux运用中间件处理事件.png
需要注意的是这些中间件会按照指定的顺序一次处理传入的action,只有排在前面的中间件完成任务之后,后面的中间件才有机会继续处理 action。

2.2 中间件机制

Redux是通过applyMiddleware方法来加载中间件的,因此我们首先来看一下applyMiddleware方法的源码

//compose 可以接受一组函数参数,从右到左来组合多个函数,然后返回一个组合函数。
import compose from './compose'; 
export default function applyMiddleware(...middlewares) { 
return (next) => (reducer, initialState) => { 
//为中间件分发store
let store = next(reducer, initialState); 
let dispatch = store.dispatch; 
let chain = []; 
//将store 的 getState方法和 dispatch 方法赋值给middlewareAPI
var middlewareAPI = { 
getState: store.getState, 
//使用匿名函数,保证最终compose 结束后的新dispatch保持一致
dispatch: (action) => dispatch(action), 
}; 
//chain: [f1, f2, ... , fx, ..., fn]
chain = middlewares.map(middleware => middleware(middlewareAPI)); 
//利用compose将所有中间件串联起来,
dispatch = compose(...chain)(store.dispatch); 
return { 
...store, 
dispatch, 
}; 
} 
}

其中 compose就是将传入的所有函数组合成一个新的函数,Redux中的compose实现方式如下所示:

function compose(...funcs) { 
  return arg => funcs.reduceRight((composed, f) => f(composed), arg); 
}

当调用 reduceRight时依次从 funcs 数组的右端取一个函数 fn 拿来执行,fn的参数 composed 就是前一次 f(n+1) 执行的结果假如n=3,新的 dispatch = f1(f2(f3(store.dispatch))))。
接下来我们看看一个最简单的中间件是如何实现的:

export default (dispatch, getState) => next => action => next(action)

其中的next是一个函数,当调用它时,表示一个中间件已经完成了任务,然后将这个action传递给下一个中间件并作为参数传递给next函数处理action。
那么使用next(action)和store.dispatch(action)有何区别呢?简单的来说store.dispatch(action)都是和新的dispatch一样的,但是next(action)是进入下一个中间件的操作,所以如果某个中间件使用了store.dispatch(action),就相当于把整个中间件的传递过程重头来一遍。具体如图所示:

相关文章

  • Redux 中间件源码清源

    网上的Redux中间件原理解释多有疏漏,譬如我在多篇blog上看到Redux中间件解释以及Redux中间件深入浅出...

  • [源码] Redux React-Redux01

    redux中间件洋葱模型imageimage redux中间件注意点image 导航 [深入01] 执行上下文[h...

  • 深入Redux及其中间件

    1. Redux简介 Redux的核心API主要有两个:createStore和reducer。 createSt...

  • 阅迹(二)

    3.23 看过 javascript函数式编程入门小结 [译]深入浅出Redux中间件 Redux 中文文档 [章...

  • react 面试

    react redux (所有数据都放入redux管理) 1、redux中间件原理(middleware) 中间件...

  • 2-Redux中间件

    Redux 中间件 [toc] Redux 中间件的作用 Reudx 中的中间件是通过对 dispatch 进行的...

  • Day17. Redux深入

    如何使用redux-thunk 中间件的使用, redux-thunk redux-devtools redux开...

  • react技术栈

    关于 Redux 中间件 Redux 的中间件是定义一个函数,对 dispatch 进行改造,在发出 action...

  • Redux-saga

    Redux-saga 概述 redux-saga是一个用于管理redux应用异步操作的中间件,redux-saga...

  • react项目中引入redux+react-router的一些写

    Redux + react-router 关于redux中间件的理解https://zhuanlan.zhihu....

网友评论

    本文标题:深入Redux及其中间件

    本文链接:https://www.haomeiwen.com/subject/ykhbqctx.html