# Redux-Saga

前面看过我对redux-thunk的使用和原理分析的,应该明白redux-thunk其实就是把action当成一个方法,把redux的dispatch作为参数传入,这样我们就可以在action写入自己的异步处理,拿到数据之后手动dispatch一个action,reducer再进行处理。
这个原理很简单,但是去有几个缺点。一来,当逻辑比较复杂的时候,action会变得比较臃肿,二来,将异步处理放入到action会感觉有点使本来就复杂的redux更加难以读懂。

# 什么是Redux-Saga?教程

说起来的比较复杂,我也懒得作详细的解释。其实和redux-thunk不同的是它将异步逻辑独立出来了,这样的话逻辑代码和redux就分开了。你可以类似像MVC一样,saga像model去获取数据,redux像controller对数据进行处理,view则是拿到数据对页面渲染。

# 简单实用

  1. redux应用中间件
import {createStore, applyMiddleware} from 'redux'
import createSagaMiddleware from 'redux-saga'
import rootSaga from './sagas'
import reducer from './reducers'
import Counter from './Counter'

const sagaMiddleware = createSagaMiddleware()
// 应用中间件
const store = createStore(
  reducer,
  applyMiddleware(sagaMiddleware)
)
// 运行soga
sagaMiddleware.run(rootSaga)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
  1. sagas.js
import {delay} from 'redux-saga'
import {put, takeEvery, all, call} from 'redux-saga/effects'

// 类似异步请求操作
export function* incrementAsync() {
  yield call(delay, 1000)
  yield put({type: 'INCREMENT'})
}
// 类似定义一个action,当发送的action.type 为INCREMENT_ASYNC,将会触发incrementAsync方法
export function* watchIncrementAsync() {
  yield takeEvery('INCREMENT_ASYNC', incrementAsync)
}

export default function* rootSaga() {
  yield all([
    watchIncrementAsync()
  ])
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# 这是一个示例demo