首页 > 其他分享 >Redux中的Enhancer 与 Middleware

Redux中的Enhancer 与 Middleware

时间:2023-02-24 20:46:02浏览次数:39  
标签:Enhancer function const Middleware dispatch action import Redux store

1. Enhancer 改变和加强store的接口方法

import { createStore, compose } from 'redux'
import rootReducer from './reducer'
import {
  sayHiOnDispatch,
  includeMeaningOfLife
} from './exampleAddons/enhancers'

const composedEnhancer = compose(sayHiOnDispatch, includeMeaningOfLife)

const store = createStore(rootReducer,  composedEnhancer)

export default store

2. 中间件(Middleware)

Middleware是一种特殊的enhancer,旨在加强和改变dispatch的行为,在action到达reducer之前提供
扩展功能,比如进行异步或者其他副作用操作。

  • 用中间件创建store
import { createStore, applyMiddleware } from 'redux'
import rootReducer from './reducer'
import { print1, print2, print3 } from './exampleAddons/middleware'

const middlewareEnhancer = applyMiddleware(print1, print2, print3)

// Pass enhancer as the second arg, since there's no preloadedState
const store = createStore(rootReducer, middlewareEnhancer)

export default store
  • 编写自定义中间件
    ES5 functions
// Outer function:
function exampleMiddleware(storeAPI) {
  return function wrapDispatch(next) {
    return function handleAction(action) {
      // Do anything here: pass the action onwards with next(action),
      // or restart the pipeline with storeAPI.dispatch(action)
      // Can also use storeAPI.getState() here

      return next(action)
    }
  }
}

ES6 arrow functions

const anotherExampleMiddleware = storeAPI => next => action => {
  // Do something in here, when each action is dispatched
  return next(action)
}

3. 异步函数中间件

  • 自定义异步函数中间件
const asyncFunctionMiddleware = storeAPI => next => action => {
  // If the "action" is actually a function instead...
  if (typeof action === 'function') {
    // then call the function and pass `dispatch` and `getState` as arguments
    return action(storeAPI.dispatch, storeAPI.getState)
  }
  // Otherwise, it's a normal action - send it onwards
  return next(action)
}

const middlewareEnhancer = applyMiddleware(asyncFunctionMiddleware)
const store = createStore(rootReducer, middlewareEnhancer)

// Write a function that has `dispatch` and `getState` as arguments
const fetchSomeData = (dispatch, getState) => {
  // Make an async HTTP request
  client.get('todos').then(todos => {
    // Dispatch an action with the todos we received
    dispatch({ type: 'todos/todosLoaded', payload: todos })
    // Check the updated store state after dispatching
    const allTodos = getState().todos
    console.log('Number of todos after loading: ', allTodos.length)
  })
}

// Pass the _function_ we wrote to `dispatch`
store.dispatch(fetchSomeData)
// logs: 'Number of todos after loading: ###'
  • 使用redux-thunk
import { createStore, applyMiddleware } from 'redux'
import thunkMiddleware from 'redux-thunk'
import { composeWithDevTools } from 'redux-devtools-extension'
import rootReducer from './reducer'

const composedEnhancer = composeWithDevTools(applyMiddleware(thunkMiddleware))

// The store now has the ability to accept thunk functions in `dispatch`
const store = createStore(rootReducer, composedEnhancer)
export default store

标签:Enhancer,function,const,Middleware,dispatch,action,import,Redux,store
From: https://www.cnblogs.com/xiaodi-js/p/17153052.html

相关文章

  • 人人能读懂redux原理剖析
    一、Redux是什么?众所周知,Redux最早运用于React框架中,是一个全局状态管理器。Redux解决了在开发过程中数据无限层层传递而引发的一系列问题,因此我们有必要来了解一下Redux......
  • rtk(redux)快速实践 创建一个Post part3 显示和编辑单个文章 添加用户 存储文章日期
    啊,标题好长捏。这篇对应文档这里呢!经过上一节,我们实践了最基本的rtk维护状态的流程在第三节:基本数据流中,我们看到了如何从一个空的Redux+React项目设置开始,添加一......
  • Redux Toolkit 的使用方法
    ReduxToolkit是什么?ReduxToolkit是Redux官方强烈推荐,开箱即用的一个高效的Redux开发工具集。它旨在成为标准的Redux逻辑开发模式,我们强烈建议你使用它。它包括......
  • react中redux怎么使用
    一、redux是什么?redux就是react全局状态管理,作用是存放全局数据 二、核心state:存放数据reducer:修改仓库数据是一个函数,参数一:仓库中的数据,参数2:行为act......
  • redux 对thunk的补充(createAsyncThunk和extraReducers)
    补充thunk的编写模式上个章节,我们提到了thunk。我想了一下,有一个重点没说。1.reducer就是用于处理数据的逻辑2.reducer中不能放置任何异步的逻辑基于上面两点,thunk必......
  • Redux的理解?Redux的工作原理
    一、是什么React是用于构建用户界面的,帮助我们解决渲染DOM的过程而在整个应用中会存在很多个组件,每个组件的state是由自身进行管理,包括组件定义自身的state、组件之间的......
  • 使用 Scrapy 框架的 Middleware
    启用Middleware图中内容原本是注释的,去掉注释即可'middlewares.'后面接的是middle类的名字,是可以改的。改成如图的形式就算启用指定名称的middleware了。函数详解......
  • redux-toolkit详解
    简述redux-toolkit是 Redux官方强烈推荐,开箱即用的一个高效的Redux开发工具集,本质是对redux的封装,方便我们写reducer、actioncreator和继承类似thunk的中间件。......
  • 简单解释 什么是Redux
    我已经有一段时间没有写任何东西了。我收到了很多关于在Redux上创建教程的消息!所以就在这里。我花了很多天时间使本教程更加简单易懂。现在让我们开始吧^_^在进入什么是R......
  • react状态管理redux
    redux产生的历史背景当我们的前端系统变得复杂,包含众多子组件,特别是包含很长一条子组件链时。我们的state管理就会非常繁琐,例如如下图,如果Child11需要用到App里的stat......