若是没有中间件,store.dispatch只能接收一个普通对象做为action。在处理异步action时,咱们须要在异步回调或者promise函数then内,async函数await以后dispatch。redux
dispatch({ type:'before-load' }) fetch('http://myapi.com/${userId}').then({ response =>dispatch({ type:'load', payload:response }) })
这样作确实能够解决问题,特别是在小型项目中,高效,可读性强。 但缺点是须要在组件中写大量的异步逻辑代码,不能将异步过程(例如异步获取数据)与dispatch抽象出来进行复用。而采用相似redux-thunk之类的中间件可使得dispatch可以接收不单单是普通对象做为action。例如:api
function load(userId){ return function(dispatch,getState){ dispatch({ type:'before-load' }) fetch('http://myapi.com/${userId}').then({ response =>dispatch({ type:'load', payload:response }) }) } } //使用方式 dispatch(load(userId))
使用中间件可让你采用本身方便的方式dispatch异步action,下面介绍常见的三种。promise
function createThunkMiddleware(extraArgument) { return ({ dispatch, getState }) => next => action => { if (typeof action === 'function') { return action(dispatch, getState, extraArgument); } return next(action); }; } const thunk = createThunkMiddleware(); thunk.withExtraArgument = createThunkMiddleware; export default thunk;
使用redux-promise能够将action或者action的payload写成promise形式。 源码:浏览器
export default function promiseMiddleware({ dispatch }) { return next => action => { if (!isFSA(action)) { return isPromise(action) ? action.then(dispatch) : next(action); } return isPromise(action.payload) ? action.payload .then(result => dispatch({ ...action, payload: result })) .catch(error => { dispatch({ ...action, payload: error, error: true }); return Promise.reject(error); }) : next(action); }; }
redux-saga
是一个用于管理应用程序 Side Effect(反作用,例如异步获取数据,访问浏览器缓存等)的 library,它的目标是让反作用管理更容易,执行更高效,测试更简单,在处理故障时更容易缓存
import { call, put, takeEvery, takeLatest} from 'redux-saga/effects'; //复杂的异步流程操做 function* fetchUser(action){ try{ const user = yield call(API.fetchUser, action.payload); yield put({type:"USER_FETCH_SUCCEEDED",user:user}) }catch(e){ yield put({type:"USER_FETCH_FAILED",message:e.message}) } } //监听dispatch,调用相应函数进行处理 function* mainSaga(){ yield takeEvery("USER_FETCH_REQUESTED",fetchUser); } //在store中注入saga中间件 import {createStore,applyMiddleware} from 'redux'; import createSagaMiddleware from 'redux-saga'; import reducer from './reducers'; import mainSaga from './mainSaga'; const sagaMiddleware = createSagaMiddleware(); const store = createStore(reducer,initalState,applyMiddleware(sagaMiddleware)); sagaMiddleware.run(mainSaga)
为了测试方便,在generator中不当即执行异步调用,而是使用call、apply等effects建立一条描述函数调用的对象,saga中间件确保执行函数调用并在响应被resolve时恢复generator。app
function* fetchProducts() { const products = yield Api.fetch('/products') dispatch({ type: 'PRODUCTS_RECEIVED', products }) } //便于测试 function* fetchProducts() { const products = yield call(Api.fetch, '/products') //便于测试dispatch yield put({ type: 'PRODUCTS_RECEIVED', products }) // ... } // Effect -> 调用 Api.fetch 函数并传递 `./products` 做为参数 { CALL: { fn: Api.fetch, args: ['./products'] } }
saga能够经过使用effect建立器、effect组合器、saga辅助函数来构建复杂的控制流。异步
effect建立器:async
args
调用函数 fn
。fn
effect组合器:ide
race:阻塞性effect:用来命令 middleware 在多个 Effect 间运行 竞赛(Race)函数
function fetchUsersSaga { const { response, cancel } = yield race({ response: call(fetchUsers), cancel: take(CANCEL_FETCH) }) }
all: 当 array 或 object 中有阻塞型 effect 的时候阻塞,用来命令 middleware 并行地运行多个 Effect,并等待它们所有完成
function* mySaga() { const [customers, products] = yield all([ call(fetchCustomers), call(fetchProducts) ]) }
effect辅助函数:
takeEvery:非阻塞性effect,在发起(dispatch)到 Store 而且匹配 pattern
的每个 action 上派生一个 saga
const takeEvery = (patternOrChannel, saga, ...args) => fork(function*() { while (true) { const action = yield take(patternOrChannel) yield fork(saga, ...args.concat(action)) } })
takeLatest:非阻塞性,在发起到 Store 而且匹配 pattern
的每个 action 上派生一个 saga
。并自动取消以前全部已经启动但仍在执行中的 saga
任务。
const takeLatest = (patternOrChannel, saga, ...args) => fork(function*() { let lastTask while (true) { const action = yield take(patternOrChannel) if (lastTask) { yield cancel(lastTask) // 若是任务已经结束,cancel 则是空操做 } lastTask = yield fork(saga, ...args.concat(action)) } })
throttle:非阻塞性,在 ms
毫秒内将暂停派生新的任务
const throttle = (ms, pattern, task, ...args) => fork(function*() { const throttleChannel = yield actionChannel(pattern) while (true) { const action = yield take(throttleChannel) yield fork(task, ...args, action) yield delay(ms) } })