标签:action creates function work 合并 default cin 执行器 ons
redux-saga是一个redux的中间件。普通的reducer函数只能是纯函数(输出由输入决定;不会改变作用域之外的值),并且只能处理同步操作。而redux-saga可以监听并执行异步操作和其他副作用。
redux-saga分为三类:
启动saga的唯一入口; 启动的时候和reducer类似,只能有一个saga(generator函数)。
监听被dispatch触发的action, 当接受到action或者知道其被触发时,触发worker saga执行
进行异步操作
import creteReactSagaMiddleware from ‘redux-saga‘; const sagaMiddleware = creteReactSagaMiddleware(); let store = applyMiddleware(sagaMiddleware)(createStore)(reducer);
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;
标签:action creates function work 合并 default cin 执行器 ons
原文地址:https://www.cnblogs.com/lyraLee/p/12079086.html