默认情况下,Redux 只能处理同步数据流。实际开发中,状态的更新、获取,通常是使用异步操作,可以通过 Redux中间件来实现
作用:处理具有副作用(side effect)的功能
优点:可以串联、组合,在一个项目中使用多个中间件
执行时机:在 dispatching action 和 reducer 之间
没有中间件:dispatch(action) ==> reducer
使用中间件:dispatch(action) ==> 执行中间件代码 ==> reducer
原理:封装了 redux 的 dispatch 方法
没有中间件:store.dispatch() 就是 Redux 库提供的 dispatch 方法,用来发起状态更新
使用中间件:store.dispatch() 就是中间件封装处理后的 dispatch,最终会调用 Redux 的dispatch方法发起状态更新
redux-logger 中间件:记录日志信息
import { createStore, applyMiddleware } from 'redux'
import logger from 'redux-logger'
import rootReducer from './reducers'
const store = createStore(rootReducer, applyMiddleware(logger))
// 如果中间件中使用 logger 中间件,logger 中间件应该出现在 applyMiddleware 的最后一个参数
redux-thunk 中间件:可以处理函数形式的 action,函数形式的 action 中就可以执行异步操作
const thunkAction = () => {
// 注意:此处返回的是一个函数,返回的函数有两个参数:
// 第一个参数:dispatch 函数,用来分发 action
// 第二个参数:getState 函数,用来获取 redux 状态
return (dispatch, getState) => {
setTimeout(() => {
// 执行异步操作
// 在异步操作成功后,可以继续分发对象形式的 action 来更新状态
}, 1000)
}
}
// 使用 redux-thunk 中间件后,action 既可以是对象,又可以是函数
redux-devtools-extension 中间件:可以查看 Redux 状态
import thunk from 'redux-thunk'
// 导入
import { composeWithDevTools } from 'redux-devtools-extension'
// 调用函数 将 applyMiddleware() 作为参数传入
const store = createStore(reducer, composeWithDevTools(applyMiddleware(thunk)))
export default store
// 打开浏览器的 redux 开发者工具使用