摘要:在的中,可以使用或者等來監聽某個,當某個觸發后,可以使用等發起異步操作,操作完成后使用函數觸發,同步更新,從而完成整個的更新。對于何時響應和如何響應,并沒有控制權。的作用是用來取消一個還未返回的任務。
項目截圖 redux-saga介紹項目地址
眾所周知,react僅僅是作用在View層的前端框架,redux作為前端的“數據庫”,完美!但是依舊殘留著前端一直以來的詬病=>異步。
所以就少不了有很多的中間件(middleware)來處理這些數據,而redux-saga就是其中之一。
不要把redux-saga(下面統稱為saga)想的多么牛逼,其實他就是一個輔助函數,但是榮耀里輔助拿MVP也不少哈~。
Saga最大的特點就是它可以讓你用同步的方式寫異步的代碼!想象下,如果它能夠用來監聽你的異步action,然后又用同步的方式去處理。那么,你的react-redux是不是就輕松了很多!
官方介紹,請移步redux-saga
saga相當于在redux原有的數據流中多了一層監控,捕獲監聽到的action,進行處理后,put一個新的action給相應的reducer去處理。
基本用法1、 使用createSagaMiddleware方法創建saga 的Middleware,然后在創建的redux的store時,使用applyMiddleware函數將創建的saga Middleware實例綁定到store上,最后可以調用saga Middleware的run函數來執行某個或者某些Middleware。
2、 在saga的Middleware中,可以使用takeEvery或者takeLatest等API來監聽某個action,當某個action觸發后,saga可以使用call、fetch等api發起異步操作,操作完成后使用put函數觸發action,同步更新state,從而完成整個State的更新。
下面介紹saga的API,boring~~~所以先來點動力吧
流程拆分更細,應用的邏輯和view更加的清晰,分工明確。異步的action和復雜邏輯的action都可以放到saga中去處理。模塊更加的干凈
因為使用了 Generator,redux-saga讓你可以用同步的方式寫異步代碼
能容易地測試 Generator 里所有的業務邏輯
可以通過監聽Action 來進行前端的打點日志記錄,減少侵入式打點對代碼的侵入程度
。。。
走馬觀花API(安裝啥的步驟直接略過) takeEvery用來監聽action,每個action都觸發一次,如果其對應是異步操作的話,每次都發起異步請求,而不論上次的請求是否返回
import { takeEvery } from "redux-saga/effects" function* watchFetchData() { yield takeEvery("FETCH_REQUESTED", fetchData) }takeLatest
作用同takeEvery一樣,唯一的區別是它只關注最后,也就是最近一次發起的異步請求,如果上次請求還未返回,則會被取消。
function* watchFetchData() { yield takeLatest("FETCH_REQUESTED", fetchData) }redux Effects
在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用來調用異步函數,將異步函數和函數參數作為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}) } }take
等待 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}) } }put
觸發某一個action,類似于react中的dispatch
實例如上
select作用和 redux thunk 中的 getState 相同。通常會與reselect庫配合使用
fork非阻塞任務調用機制:上面我們介紹過call可以用來發起異步操作,但是相對于generator函數來說,call操作是阻塞的,只有等promise回來后才能繼續執行,而fork是非阻塞的 ,當調用fork啟動一個任務時,該任務在后臺繼續執行,從而使得我們的執行流能繼續往下執行而不必一定要等待返回。
cancelcancel的作用是用來取消一個還未返回的fork任務。防止fork的任務等待時間太長或者其他邏輯錯誤。
allall提供了一種并行執行異步請求的方式。之前介紹過執行異步請求的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
有時候當我們并行的發起多個異步操作時,我們并不一定需要等待所有操作完成,而只需要有一個操作完成就可以繼續執行流。這就是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") }) } }actionChannel
在之前的操作中,所有的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都是沒有用到,常用的基本也就這么些了
這里我放兩個實際項目中代碼實例,大家可以看看熟悉下上面說到的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
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/88528.html
摘要:項目的架構也是最近在各種探討研究。還求大神多指點項目技術總結技術棧項目結構探究初體驗關于項目中的配置說明項目簡單說明開發這一套,我個人的理解是體現的是代碼分層職責分離的編程思想邏輯與視圖嚴格區分。前端依舊使用技術棧完成。 項目地址:https://github.com/Nealyang/R...技術棧:react、react-router4.x 、 react-redux 、 webp...
該demo使用的是webpack2.*來配置的,很多配置項都產生了變化,踩了不少坑.目前還在逐步完善中,webpack是一部一部配置來的。后端數據使用nodejs來開發模擬。GitHub項目地址。 showImg(https://segmentfault.com/img/remote/1460000009665620); 歡迎大家提問題。
摘要:項目簡介此項目是學習過程中跟著慕課網做的一個練手項目,模仿大眾點評做的一個,項目不是很復雜,適合有一定基礎的同學參考。慕課網地址項目的前端界面使用編寫,后端使用的框架搭建,后臺返回的數據全部是模擬的數據,不涉及數據庫交互。 項目簡介 此項目是學習react+redux過程中跟著慕課網做的一個練手項目,模仿大眾點評做的一個webapp,項目不是很復雜,適合有一定react+redux基礎...
摘要:通過創建將所有的異步操作邏輯收集在一個地方集中處理,可以用來代替中間件。 redux-saga框架使用詳解及Demo教程 前面我們講解過redux框架和dva框架的基本使用,因為dva框架中effects模塊設計到了redux-saga中的知識點,可能有的同學們會用dva框架,但是對redux-saga又不是很熟悉,今天我們就來簡單的講解下saga框架的主要API和如何配合redux框...
閱讀 2676·2023-04-25 20:19
閱讀 1930·2021-11-24 09:38
閱讀 1632·2021-11-16 11:44
閱讀 4341·2021-09-02 15:40
閱讀 1317·2019-08-30 15:55
閱讀 2022·2019-08-30 15:52
閱讀 3759·2019-08-29 17:20
閱讀 2247·2019-08-29 13:48