redux-saga

redux-saga是一个redux的中间件。普通的reducer函数只能是纯函数(输出由输入决定;不会改变作用域之外的值),并且只能处理同步操作。而redux-saga可以监听并执行异步操作和其他副作用。

1. redux-saga分类

redux-saga分为三类:

1. root saga

启动saga的唯一入口; 启动的时候和reducer类似,只能有一个saga(generator函数)。

2. watcher saga

监听被dispatch触发的action, 当接受到action或者知道其被触发时,触发worker saga执行

3. worker saga

进行异步操作

2. redux-saga的用法

1. 生成中间件并应用
import creteReactSagaMiddleware from ‘redux-saga‘;

const sagaMiddleware = creteReactSagaMiddleware();
let store = applyMiddleware(sagaMiddleware)(createStore)(reducer);
2. 合并sagas为根saga并启动根saga

1. 用all方法合并saga

import { all } from ‘redux-saga/effects‘;
import hellosage from ‘./sagas/hellosaga‘;
import watcherIncrease from ‘./sagas/increatesaga‘;

export default function* () {
  yield all([
    watcherIncrease(),
    hellosage()
  ])
}

/***./sagas/increatesaga***/
import { takeEvery, put, delay, call } from ‘redux-saga/effects‘;
import * as types from ‘../actions/action-types‘;

function* watcherIncrease() {
  // 监听每一次的ASYNCINCREASE操作
  // 监听到后自动调用workerSaga, 实现异步操作等
  yield takeEvery(types.ASYNCINCREASE, workerSaga);
}

function* workerSaga() {
  // 延迟1000秒;将异步操作按照同步写法
  yield delay(1000); //还可以写作:yield call(delay, 1000);
  // 触发同步操作
  yield put({type: types.INCREASE});
}

export default watcherIncrease

2. 启动根saga

import { createStore, applyMiddleware } from ‘redux‘;
import reducer from ‘./reducers‘;
import rootSaga from ‘./rootsaga‘;
import creteReactSagaMiddleware from ‘redux-saga‘;

const sagaMiddleware = creteReactSagaMiddleware();
let store = applyMiddleware(sagaMiddleware)(createStore)(reducer);

// sagaMiddleware是一个generator函数的执行器
sagaMiddleware.run(rootSaga);

export default store;