Day 23 - Redux middleware 介入处理非同步

如果有错误,欢迎留言指教~ Q_Q 没写完啦

当每次 action 被 dispatch, state 就会立刻被更新

那要如何让 Redux 可以处理非同步呢?

Middleware 是什麽?

Middleware 是一个中介层

在 dispatch action 後进入 reducer 之前

可以让我们做一些介入 action 的时间点

透过 Middleware ,可以处理非同步事件、log、调整或停止 action

在 Redux 中并没有限制 Middleware 的数量,因此我们可以有很多个 middleware

middleware 一个接着一个 middleware

每个 middleware 会检查这是不是这次需要执行的 action

如果不是就会 next 给下一个 middleware 继续处理。

如何使用

middleware

const logger = store => next => action => {
  console.log('dispatching', action)
  let result = next(action)
  console.log('next state', store.getState())
  return result
}

const crashReporter = store => next => action => {
  try {
    return next(action)
  } catch (err) {
    console.error('Caught an exception!', err)
    Raven.captureException(err, {
      extra: {
        action,
        state: store.getState()
      }
    })
    throw err
  }
}

把它运用到 Redux store 中:

将多个 middleware 依序传进 applyMiddleware()

告诉 createStore() 如何处理 middleware

import { createStore, combineReducers, applyMiddleware } from 'redux'

let todoApp = combineReducers(reducers)
let store = createStore(
  todoApp,
  applyMiddleware(logger, crashReporter)
)

现在任何被 dispatch 到 store 实体的 action 都将经过 logger 和 crashReporter:

// 将经过 logger 和 crashReporter 两个 middleware!
store.dispatch(addTodo('Use Redux'))

ref

  1. https://chentsulin.github.io/redux/docs/advanced/AsyncActions.html

<<:  Day26 - 部属到正式环境 (1)

>>:  [访谈] APCS x 竞程选手 Colten

Day 15 - [语料库模型] 03-语料读取&资料格式转换

今天的主题是介绍如何读取 CSV (之前从各个网站爬下来的问答集),并将资料转成後面制作语料库模型要...

[Day 27 - 小试身手] Todolist with React (2)

在上一章Todolist with React (1),建立了专案环境、并且拆离 UI 设定好所有...

GitHub Action YAML 撰写技巧 - 环境变数(Environment Variables) 与 秘密 (Secrets)

今天要提到一些关於 GitHub Action 内撰写 YAML 一些技巧,环境变数 (Enviro...

Day10-使用 create-react-app 部署第一个 React static Web

承接昨天的部分 先使用 create-react-app 将原本的静态页面置换掉 $ npx cre...

javascript(event)(DAY20)

之前的文章中有介绍到事件处理函式的用途,这边在简单复习一下event是做什麽用的,主要是监听使用者的...