阅读 13

一句话说清楚redux-saga

saga github.com/redux-saga/…

一句话redux-saga

创建store的时候,我根据官方文档的配,从redux-saga中引入 createSagaMiddleware, 通过执行createSagaMiddleware函数创建sagaMiddleware. 然后创建sagas.js文件并引入。然后通过sagamiddleware.run()去运行这个文件。 在sagae.js里面,一定要导出一个generator函数。在这个generator函数中写一些逻辑。saga提供一个takeEvery()函数,这个函数两个参数,第一个是接收的type,第二个参数是一个函数。当我接收到从action匹配到的类型时候,,我会执行后面的方法。这个方法也是一个generator函数,他会去取数据,取数据可以是异步的,取完数据之后会在创建一个action,用saga提供的push方法发送这个action,给到store,这时候store,将这个action给到reducer,这时候reducer会去匹配派发过来的action,匹配成功之后,reducer就会将获取过来的数据替换掉state里的内容。这时候异步获取的数据就会渲染在组件里了。

redux-thunk

thunk是允许action为一个函数,dispatch(action)之后会在action里判断,若为函数执行函数,所以可以在action里编写异步代码,等执行完之后在派发一个action,这个type就是对象,reducer就会执行。

redux-saga redux-thunk区别

saga是将异步操作分离在saga.js里面,thunk是在active里处理异步操作。saga提供非常多的api,thunk几乎没有api。在处理大型项目时候,saga会优于thunk。

redux 中间件

中间件是store和action的中间,对dispatch (action)进行了升级。

main.js

import { createStore, applyMiddleware } from 'redux'
import createSagaMiddleware from 'redux-saga'

import reducer from './reducers'
import mySaga from './sagas'

// create the saga middleware
const sagaMiddleware = createSagaMiddleware()
// mount it on the Store
const store = createStore(
  reducer,
  applyMiddleware(sagaMiddleware)
)

// then run the saga
sagaMiddleware.run(mySaga)

// render the application

复制代码

sagas.js

import { call, put, takeEvery, takeLatest } from 'redux-saga/effects'
import Api from '...'

// worker Saga: will be fired on USER_FETCH_REQUESTED actions
function* fetchUser(action) {
   try {
      const user = yield call(Api.fetchUser, action.payload.userId);
      yield put({type: "USER_FETCH_SUCCEEDED", user: user});
   } catch (e) {
      yield put({type: "USER_FETCH_FAILED", message: e.message});
   }
}

/*
  Starts fetchUser on each dispatched `USER_FETCH_REQUESTED` action.
  Allows concurrent fetches of user.
*/
function* mySaga() {
  yield takeEvery("USER_FETCH_REQUESTED", fetchUser);
}

/*
  Alternatively you may use takeLatest.

  Does not allow concurrent fetches of user. If "USER_FETCH_REQUESTED" gets
  dispatched while a fetch is already pending, that pending fetch is cancelled
  and only the latest one will be run.
*/
function* mySaga() {
  yield takeLatest("USER_FETCH_REQUESTED", fetchUser);
}

export default mySaga;

复制代码
关注下面的标签,发现更多相似文章
评论