摘要:在的中,可以使用或者等來監(jiān)聽某個(gè),當(dāng)某個(gè)觸發(fā)后,可以使用等發(fā)起異步操作,操作完成后使用函數(shù)觸發(fā),同步更新,從而完成整個(gè)的更新。對(duì)于何時(shí)響應(yīng)和如何響應(yīng),并沒有控制權(quán)。的作用是用來取消一個(gè)還未返回的任務(wù)。
項(xiàng)目截圖 redux-saga介紹項(xiàng)目地址
眾所周知,react僅僅是作用在View層的前端框架,redux作為前端的“數(shù)據(jù)庫”,完美!但是依舊殘留著前端一直以來的詬病=>異步。
所以就少不了有很多的中間件(middleware)來處理這些數(shù)據(jù),而redux-saga就是其中之一。
不要把redux-saga(下面統(tǒng)稱為saga)想的多么牛逼,其實(shí)他就是一個(gè)輔助函數(shù),但是榮耀里輔助拿MVP也不少哈~。
Saga最大的特點(diǎn)就是它可以讓你用同步的方式寫異步的代碼!想象下,如果它能夠用來監(jiān)聽你的異步action,然后又用同步的方式去處理。那么,你的react-redux是不是就輕松了很多!
官方介紹,請(qǐng)移步redux-saga
saga相當(dāng)于在redux原有的數(shù)據(jù)流中多了一層監(jiān)控,捕獲監(jiān)聽到的action,進(jìn)行處理后,put一個(gè)新的action給相應(yīng)的reducer去處理。
基本用法1、 使用createSagaMiddleware方法創(chuàng)建saga 的Middleware,然后在創(chuàng)建的redux的store時(shí),使用applyMiddleware函數(shù)將創(chuàng)建的saga Middleware實(shí)例綁定到store上,最后可以調(diào)用saga Middleware的run函數(shù)來執(zhí)行某個(gè)或者某些Middleware。
2、 在saga的Middleware中,可以使用takeEvery或者takeLatest等API來監(jiān)聽某個(gè)action,當(dāng)某個(gè)action觸發(fā)后,saga可以使用call、fetch等api發(fā)起異步操作,操作完成后使用put函數(shù)觸發(fā)action,同步更新state,從而完成整個(gè)State的更新。
下面介紹saga的API,boring~~~所以先來點(diǎn)動(dòng)力吧
流程拆分更細(xì),應(yīng)用的邏輯和view更加的清晰,分工明確。異步的action和復(fù)雜邏輯的action都可以放到saga中去處理。模塊更加的干凈
因?yàn)槭褂昧?Generator,redux-saga讓你可以用同步的方式寫異步代碼
能容易地測(cè)試 Generator 里所有的業(yè)務(wù)邏輯
可以通過監(jiān)聽Action 來進(jìn)行前端的打點(diǎn)日志記錄,減少侵入式打點(diǎn)對(duì)代碼的侵入程度
。。。
走馬觀花API(安裝啥的步驟直接略過) takeEvery用來監(jiān)聽action,每個(gè)action都觸發(fā)一次,如果其對(duì)應(yīng)是異步操作的話,每次都發(fā)起異步請(qǐng)求,而不論上次的請(qǐng)求是否返回
import { takeEvery } from "redux-saga/effects" function* watchFetchData() { yield takeEvery("FETCH_REQUESTED", fetchData) }takeLatest
作用同takeEvery一樣,唯一的區(qū)別是它只關(guān)注最后,也就是最近一次發(fā)起的異步請(qǐng)求,如果上次請(qǐng)求還未返回,則會(huì)被取消。
function* watchFetchData() { yield takeLatest("FETCH_REQUESTED", fetchData) }redux Effects
在saga的世界里,所有的任務(wù)都通用 yield Effect 來完成,Effect暫時(shí)就理解為一個(gè)任務(wù)單元吧,其實(shí)就是一個(gè)JavaScript的對(duì)象,可以通過sagaMiddleWare進(jìn)行執(zhí)行。
重點(diǎn)說明下,在redux-saga的應(yīng)用中,所有的Effect都必須被yield后才可以被執(zhí)行。
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用來調(diào)用異步函數(shù),將異步函數(shù)和函數(shù)參數(shù)作為call函數(shù)的參數(shù)傳入,返回一個(gè)js對(duì)象。saga引入他的主要作用是方便測(cè)試,同時(shí)也能讓我們的代碼更加規(guī)范化。
同js原生的call一樣,call函數(shù)也可以指定this對(duì)象,只要把this對(duì)象當(dāng)?shù)谝粋€(gè)參數(shù)傳入call方法就好了
saga同樣提供apply函數(shù),作用同call一樣,參數(shù)形式同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}) } }take
等待 reactjs dispatch 一個(gè)匹配的action。take的表現(xiàn)同takeEvery一樣,都是監(jiān)聽某個(gè)action,但與takeEvery不同的是,他不是每次action觸發(fā)的時(shí)候都相應(yīng),而只是在執(zhí)行順序執(zhí)行到take語句時(shí)才會(huì)相應(yīng)action。
當(dāng)在genetator中使用take語句等待action時(shí),generator被阻塞,等待action被分發(fā),然后繼續(xù)往下執(zhí)行。
takeEvery只是監(jiān)聽每個(gè)action,然后執(zhí)行處理函數(shù)。對(duì)于何時(shí)響應(yīng)action和 如何響應(yīng)action,takeEvery并沒有控制權(quán)。
而take則不一樣,我們可以在generator函數(shù)中決定何時(shí)響應(yīng)一個(gè)action,以及一個(gè)action被觸發(fā)后做什么操作。
最大區(qū)別:take只有在執(zhí)行流達(dá)到時(shí)才會(huì)響應(yīng)對(duì)應(yīng)的action,而takeEvery則一經(jīng)注冊(cè),都會(huì)響應(yīng)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}) } }put
觸發(fā)某一個(gè)action,類似于react中的dispatch
實(shí)例如上
select作用和 redux thunk 中的 getState 相同。通常會(huì)與reselect庫配合使用
fork非阻塞任務(wù)調(diào)用機(jī)制:上面我們介紹過call可以用來發(fā)起異步操作,但是相對(duì)于generator函數(shù)來說,call操作是阻塞的,只有等promise回來后才能繼續(xù)執(zhí)行,而fork是非阻塞的 ,當(dāng)調(diào)用fork啟動(dòng)一個(gè)任務(wù)時(shí),該任務(wù)在后臺(tái)繼續(xù)執(zhí)行,從而使得我們的執(zhí)行流能繼續(xù)往下執(zhí)行而不必一定要等待返回。
cancelcancel的作用是用來取消一個(gè)還未返回的fork任務(wù)。防止fork的任務(wù)等待時(shí)間太長或者其他邏輯錯(cuò)誤。
allall提供了一種并行執(zhí)行異步請(qǐng)求的方式。之前介紹過執(zhí)行異步請(qǐng)求的api中,大都是阻塞執(zhí)行,只有當(dāng)一個(gè)call操作放回后,才能執(zhí)行下一個(gè)call操作, call提供了一種類似Promise中的all操作,可以將多個(gè)異步操作作為參數(shù)參入all函數(shù)中,
如果有一個(gè)call操作失敗或者所有call操作都成功返回,則本次all操作執(zhí)行完畢。
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
有時(shí)候當(dāng)我們并行的發(fā)起多個(gè)異步操作時(shí),我們并不一定需要等待所有操作完成,而只需要有一個(gè)操作完成就可以繼續(xù)執(zhí)行流。這就是race的用處。
他可以并行的啟動(dòng)多個(gè)異步請(qǐng)求,只要有一個(gè) 請(qǐng)求返回(resolved或者reject),race操作接受正常返回的請(qǐng)求,并且將剩余的請(qǐng)求取消。
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") }) } }actionChannel
在之前的操作中,所有的action分發(fā)是順序的,但是對(duì)action的響應(yīng)是由異步任務(wù)來完成,也即是說對(duì)action的處理是無序的。
如果需要對(duì)action的有序處理的話,可以使用actionChannel函數(shù)來創(chuàng)建一個(gè)action的緩存隊(duì)列,但一個(gè)action的任務(wù)流程處理完成后,才可是執(zhí)行下一個(gè)任務(wù)流。
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從我寫的這個(gè)項(xiàng)目可以看到,其實(shí)我很多API都是沒有用到,常用的基本也就這么些了
這里我放兩個(gè)實(shí)際項(xiàng)目中代碼實(shí)例,大家可以看看熟悉下上面說到的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) }
另一個(gè)demo saga也跟我一樣,拆分了下
簡單看兩個(gè)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技術(shù)交流群:209530601
React技術(shù)棧:398240621
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/88528.html
摘要:項(xiàng)目的架構(gòu)也是最近在各種探討研究。還求大神多指點(diǎn)項(xiàng)目技術(shù)總結(jié)技術(shù)棧項(xiàng)目結(jié)構(gòu)探究初體驗(yàn)關(guān)于項(xiàng)目中的配置說明項(xiàng)目簡單說明開發(fā)這一套,我個(gè)人的理解是體現(xiàn)的是代碼分層職責(zé)分離的編程思想邏輯與視圖嚴(yán)格區(qū)分。前端依舊使用技術(shù)棧完成。 項(xiàng)目地址:https://github.com/Nealyang/R...技術(shù)棧:react、react-router4.x 、 react-redux 、 webp...
該demo使用的是webpack2.*來配置的,很多配置項(xiàng)都產(chǎn)生了變化,踩了不少坑.目前還在逐步完善中,webpack是一部一部配置來的。后端數(shù)據(jù)使用nodejs來開發(fā)模擬。GitHub項(xiàng)目地址。 showImg(https://segmentfault.com/img/remote/1460000009665620); 歡迎大家提問題。
摘要:項(xiàng)目簡介此項(xiàng)目是學(xué)習(xí)過程中跟著慕課網(wǎng)做的一個(gè)練手項(xiàng)目,模仿大眾點(diǎn)評(píng)做的一個(gè),項(xiàng)目不是很復(fù)雜,適合有一定基礎(chǔ)的同學(xué)參考。慕課網(wǎng)地址項(xiàng)目的前端界面使用編寫,后端使用的框架搭建,后臺(tái)返回的數(shù)據(jù)全部是模擬的數(shù)據(jù),不涉及數(shù)據(jù)庫交互。 項(xiàng)目簡介 此項(xiàng)目是學(xué)習(xí)react+redux過程中跟著慕課網(wǎng)做的一個(gè)練手項(xiàng)目,模仿大眾點(diǎn)評(píng)做的一個(gè)webapp,項(xiàng)目不是很復(fù)雜,適合有一定react+redux基礎(chǔ)...
摘要:通過創(chuàng)建將所有的異步操作邏輯收集在一個(gè)地方集中處理,可以用來代替中間件。 redux-saga框架使用詳解及Demo教程 前面我們講解過redux框架和dva框架的基本使用,因?yàn)閐va框架中effects模塊設(shè)計(jì)到了redux-saga中的知識(shí)點(diǎn),可能有的同學(xué)們會(huì)用dva框架,但是對(duì)redux-saga又不是很熟悉,今天我們就來簡單的講解下saga框架的主要API和如何配合redux框...
閱讀 2688·2023-04-25 20:19
閱讀 1954·2021-11-24 09:38
閱讀 1639·2021-11-16 11:44
閱讀 4378·2021-09-02 15:40
閱讀 1360·2019-08-30 15:55
閱讀 2030·2019-08-30 15:52
閱讀 3769·2019-08-29 17:20
閱讀 2282·2019-08-29 13:48