項目地址前端
衆所周知,react僅僅是做用在View層的前端框架,redux做爲前端的「數據庫」,完美!可是依舊殘留着前端一直以來的詬病=>異步。react
因此就少不了有不少的中間件(middleware)來處理這些數據,而redux-saga就是其中之一。git
不要把redux-saga(下面統稱爲saga)想的多麼牛逼,其實他就是一個輔助函數,可是榮耀裏輔助拿MVP也很多哈~。github
Saga最大的特色就是它可讓你用同步的方式寫異步的代碼!想象下,若是它可以用來監聽你的異步action,而後又用同步的方式去處理。那麼,你的react-redux是否是就輕鬆了不少!數據庫
官方介紹,請移步redux-sagaredux
saga至關於在redux原有的數據流中多了一層監控,捕獲監聽到的action,進行處理後,put一個新的action給相應的reducer去處理。api
一、 使用createSagaMiddleware方法建立saga 的Middleware,而後在建立的redux的store時,使用applyMiddleware函數將建立的saga Middleware實例綁定到store上,最後能夠調用saga Middleware的run函數來執行某個或者某些Middleware。
二、 在saga的Middleware中,可使用takeEvery或者takeLatest等API來監聽某個action,當某個action觸發後,saga可使用call、fetch等api發起異步操做,操做完成後使用put函數觸發action,同步更新state,從而完成整個State的更新。promise
下面介紹saga的API,boring~~~因此先來點動力吧緩存
流程拆分更細,應用的邏輯和view更加的清晰,分工明確。異步的action和複雜邏輯的action均可以放到saga中去處理。模塊更加的乾淨前端框架
由於使用了 Generator,redux-saga讓你能夠用同步的方式寫異步代碼
能容易地測試 Generator 裏全部的業務邏輯
能夠經過監聽Action 來進行前端的打點日誌記錄,減小侵入式打點對代碼的侵入程度
。。。
用來監聽action,每一個action都觸發一次,若是其對應是異步操做的話,每次都發起異步請求,而不論上次的請求是否返回
import { takeEvery } from 'redux-saga/effects' function* watchFetchData() { yield takeEvery('FETCH_REQUESTED', fetchData) }
做用同takeEvery同樣,惟一的區別是它只關注最後,也就是最近一次發起的異步請求,若是上次請求還未返回,則會被取消。
function* watchFetchData() { yield takeLatest('FETCH_REQUESTED', fetchData) }
在saga的世界裏,全部的任務都通用 yield Effect 來完成,Effect暫時就理解爲一個任務單元吧,其實就是一個JavaScript的對象,能夠經過sagaMiddleWare進行執行。
重點說明下,在redux-saga的應用中,全部的Effect都必須被yield後才能夠被執行。
import {fork,call} from 'redux-saga/effects' import {getAdDataFlow,getULikeDataFlow} from './components/home/homeSaga' import {getLocatioFlow} from './components/wrap/wrapSaga' import {getDetailFolw} from './components/detail/detailSaga' import {getCitiesFlow} from './components/city/citySaga' export default function* rootSaga () { yield fork(getLocatioFlow); yield fork(getAdDataFlow); yield fork(getULikeDataFlow); yield fork(getDetailFolw); yield fork(getCitiesFlow); }
call用來調用異步函數,將異步函數和函數參數做爲call函數的參數傳入,返回一個js對象。saga引入他的主要做用是方便測試,同時也能讓咱們的代碼更加規範化。
同js原生的call同樣,call函數也能夠指定this對象,只要把this對象當第一個參數傳入call方法就行了
saga一樣提供apply函數,做用同call同樣,參數形式同js原生apply方法。
export function* getAdData(url) { yield put({type:wrapActionTypes.START_FETCH}); yield delay(delayTime);//故意的 try { return yield call(get,url); } catch (error) { yield put({type:wrapActionTypes.FETCH_ERROR}) }finally { yield put({type:wrapActionTypes.FETCH_END}) } } export function* getAdDataFlow() { while (true){ let request = yield take(homeActionTypes.GET_AD); let response = yield call(getAdData,request.url); yield put({type:homeActionTypes.GET_AD_RESULT_DATA,data:response.data}) } }
等待 reactjs dispatch 一個匹配的action。take的表現同takeEvery同樣,都是監聽某個action,但與takeEvery不一樣的是,他不是每次action觸發的時候都相應,而只是在執行順序執行到take語句時纔會相應action。
當在genetator中使用take語句等待action時,generator被阻塞,等待action被分發,而後繼續往下執行。
takeEvery只是監聽每一個action,而後執行處理函數。對於什麼時候響應action和 如何響應action,takeEvery並無控制權。
而take則不同,咱們能夠在generator函數中決定什麼時候響應一個action,以及一個action被觸發後作什麼操做。
最大區別:take只有在執行流達到時纔會響應對應的action,而takeEvery則一經註冊,都會響應action。
export function* getAdDataFlow() { while (true){ let request = yield take(homeActionTypes.GET_AD); let response = yield call(getAdData,request.url); yield put({type:homeActionTypes.GET_AD_RESULT_DATA,data:response.data}) } }
觸發某一個action,相似於react中的dispatch
實例如上
做用和 redux thunk 中的 getState 相同。一般會與reselect庫配合使用
非阻塞任務調用機制:上面咱們介紹過call能夠用來發起異步操做,可是相對於generator函數來講,call操做是阻塞的,只有等promise回來後才能繼續執行,而fork是非阻塞的 ,當調用fork啓動一個任務時,該任務在後臺繼續執行,從而使得咱們的執行流能繼續往下執行而沒必要必定要等待返回。
cancel的做用是用來取消一個還未返回的fork任務。防止fork的任務等待時間太長或者其餘邏輯錯誤。
all提供了一種並行執行異步請求的方式。以前介紹過執行異步請求的api中,大都是阻塞執行,只有當一個call操做放回後,才能執行下一個call操做, call提供了一種相似Promise中的all操做,能夠將多個異步操做做爲參數參入all函數中,
若是有一個call操做失敗或者全部call操做都成功返回,則本次all操做執行完畢。
import { all, call } from 'redux-saga/effects' // correct, effects will get executed in parallel const [users, repos] = yield all([ call(fetch, '/users'), call(fetch, '/repos') ])
有時候當咱們並行的發起多個異步操做時,咱們並不必定須要等待全部操做完成,而只須要有一個操做完成就能夠繼續執行流。這就是race的用處。
他能夠並行的啓動多個異步請求,只要有一個 請求返回(resolved或者reject),race操做接受正常返回的請求,而且將剩餘的請求取消。
import { race, take, put } from 'redux-saga/effects' function* backgroundTask() { while (true) { ... } } function* watchStartBackgroundTask() { while (true) { yield take('START_BACKGROUND_TASK') yield race({ task: call(backgroundTask), cancel: take('CANCEL_TASK') }) } }
在以前的操做中,全部的action分發是順序的,可是對action的響應是由異步任務來完成,也便是說對action的處理是無序的。
若是須要對action的有序處理的話,可使用actionChannel函數來建立一個action的緩存隊列,但一個action的任務流程處理完成後,才但是執行下一個任務流。
import { take, actionChannel, call, ... } from 'redux-saga/effects' function* watchRequests() { // 1- Create a channel for request actions const requestChan = yield actionChannel('REQUEST') while (true) { // 2- take from the channel const {payload} = yield take(requestChan) // 3- Note that we're using a blocking call yield call(handleRequest, payload) } } function* handleRequest(payload) { ... }
從我寫的這個項目能夠看到,其實我不少API都是沒有用到,經常使用的基本也就這麼些了
這裏我放兩個實際項目中代碼實例,你們能夠看看熟悉下上面說到的API
rootSaga.js
// This file contains the sagas used for async actions in our app. It's divided into // "effects" that the sagas call (`authorize` and `logout`) and the actual sagas themselves, // which listen for actions. // Sagas help us gather all our side effects (network requests in this case) in one place import {hashSync} from 'bcryptjs' import genSalt from '../auth/salt' import {browserHistory} from 'react-router' import {take, call, put, fork, race} from 'redux-saga/effects' import auth from '../auth' import { SENDING_REQUEST, LOGIN_REQUEST, REGISTER_REQUEST, SET_AUTH, LOGOUT, CHANGE_FORM, REQUEST_ERROR } from '../actions/constants' /** * Effect to handle authorization * @param {string} username The username of the user * @param {string} password The password of the user * @param {object} options Options * @param {boolean} options.isRegistering Is this a register request? */ export function * authorize ({username, password, isRegistering}) { // We send an action that tells Redux we're sending a request yield put({type: SENDING_REQUEST, sending: true}) // We then try to register or log in the user, depending on the request try { let salt = genSalt(username) let hash = hashSync(password, salt) let response // For either log in or registering, we call the proper function in the `auth` // module, which is asynchronous. Because we're using generators, we can work // as if it's synchronous because we pause execution until the call is done // with `yield`! if (isRegistering) { response = yield call(auth.register, username, hash) } else { response = yield call(auth.login, username, hash) } return response } catch (error) { console.log('hi') // If we get an error we send Redux the appropiate action and return yield put({type: REQUEST_ERROR, error: error.message}) return false } finally { // When done, we tell Redux we're not in the middle of a request any more yield put({type: SENDING_REQUEST, sending: false}) } } /** * Effect to handle logging out */ export function * logout () { // We tell Redux we're in the middle of a request yield put({type: SENDING_REQUEST, sending: true}) // Similar to above, we try to log out by calling the `logout` function in the // `auth` module. If we get an error, we send an appropiate action. If we don't, // we return the response. try { let response = yield call(auth.logout) yield put({type: SENDING_REQUEST, sending: false}) return response } catch (error) { yield put({type: REQUEST_ERROR, error: error.message}) } } /** * Log in saga */ export function * loginFlow () { // Because sagas are generators, doing `while (true)` doesn't block our program // Basically here we say "this saga is always listening for actions" while (true) { // And we're listening for `LOGIN_REQUEST` actions and destructuring its payload let request = yield take(LOGIN_REQUEST) let {username, password} = request.data // A `LOGOUT` action may happen while the `authorize` effect is going on, which may // lead to a race condition. This is unlikely, but just in case, we call `race` which // returns the "winner", i.e. the one that finished first let winner = yield race({ auth: call(authorize, {username, password, isRegistering: false}), logout: take(LOGOUT) }) // If `authorize` was the winner... if (winner.auth) { // ...we send Redux appropiate actions yield put({type: SET_AUTH, newAuthState: true}) // User is logged in (authorized) yield put({type: CHANGE_FORM, newFormState: {username: '', password: ''}}) // Clear form forwardTo('/dashboard') // Go to dashboard page } } } /** * Log out saga * This is basically the same as the `if (winner.logout)` of above, just written * as a saga that is always listening to `LOGOUT` actions */ export function * logoutFlow () { while (true) { yield take(LOGOUT) yield put({type: SET_AUTH, newAuthState: false}) yield call(logout) forwardTo('/') } } /** * Register saga * Very similar to log in saga! */ export function * registerFlow () { while (true) { // We always listen to `REGISTER_REQUEST` actions let request = yield take(REGISTER_REQUEST) let {username, password} = request.data // We call the `authorize` task with the data, telling it that we are registering a user // This returns `true` if the registering was successful, `false` if not let wasSuccessful = yield call(authorize, {username, password, isRegistering: true}) // If we could register a user, we send the appropiate actions if (wasSuccessful) { yield put({type: SET_AUTH, newAuthState: true}) // User is logged in (authorized) after being registered yield put({type: CHANGE_FORM, newFormState: {username: '', password: ''}}) // Clear form forwardTo('/dashboard') // Go to dashboard page } } } // The root saga is what we actually send to Redux's middleware. In here we fork // each saga so that they are all "active" and listening. // Sagas are fired once at the start of an app and can be thought of as processes running // in the background, watching actions dispatched to the store. export default function * root () { yield fork(loginFlow) yield fork(logoutFlow) yield fork(registerFlow) } // Little helper function to abstract going to different pages function forwardTo (location) { browserHistory.push(location) }
另外一個demo saga也跟我同樣,拆分了下
簡單看兩個demo就好
index.js
import { takeLatest } from 'redux-saga'; import { fork } from 'redux-saga/effects'; import {loadUser} from './loadUser'; import {loadDashboardSequenced} from './loadDashboardSequenced'; import {loadDashboardNonSequenced} from './loadDashboardNonSequenced'; import {loadDashboardNonSequencedNonBlocking, isolatedForecast, isolatedFlight } from './loadDashboardNonSequencedNonBlocking'; function* rootSaga() { /*The saga is waiting for a action called LOAD_DASHBOARD to be activated */ yield [ fork(loadUser), takeLatest('LOAD_DASHBOARD', loadDashboardSequenced), takeLatest('LOAD_DASHBOARD_NON_SEQUENCED', loadDashboardNonSequenced), takeLatest('LOAD_DASHBOARD_NON_SEQUENCED_NON_BLOCKING', loadDashboardNonSequencedNonBlocking), fork(isolatedForecast), fork(isolatedFlight) ]; } export default rootSaga;
loadDashboardNonSequencedNonBlocking.js
import { call, put, select , take} from 'redux-saga/effects'; import {loadDeparture, loadFlight, loadForecast } from './apiCalls'; export const getUserFromState = (state) => state.user; export function* loadDashboardNonSequencedNonBlocking() { try { //Wait for the user to be loaded yield take('FETCH_USER_SUCCESS'); //Take the user info from the store const user = yield select(getUserFromState); //Get Departure information const departure = yield call(loadDeparture, user); //Update the UI yield put({type: 'FETCH_DASHBOARD3_SUCCESS', payload: {departure}}); //trigger actions for Forecast and Flight to start... //We can pass and object into the put statement yield put({type: 'FETCH_DEPARTURE3_SUCCESS', departure}); } catch(error) { yield put({type: 'FETCH_FAILED', error: error.message}); } } export function* isolatedFlight() { try { /* departure will take the value of the object passed by the put*/ const departure = yield take('FETCH_DEPARTURE3_SUCCESS'); //Flight can be called unsequenced /* BUT NON BLOCKING VS FORECAST*/ const flight = yield call(loadFlight, departure.flightID); //Tell the store we are ready to be displayed yield put({type: 'FETCH_DASHBOARD3_SUCCESS', payload: {flight}}); } catch (error) { yield put({type: 'FETCH_FAILED', error: error.message}); } } export function* isolatedForecast() { try { /* departure will take the value of the object passed by the put*/ const departure = yield take('FETCH_DEPARTURE3_SUCCESS'); const forecast = yield call(loadForecast, departure.date); yield put({type: 'FETCH_DASHBOARD3_SUCCESS', payload: { forecast }}); } catch(error) { yield put({type: 'FETCH_FAILED', error: error.message}); } }
Node.js技術交流羣:209530601
React技術棧:398240621